public UnavailableException(ConsistencyLevel consistency, int required, int alive) : base(string.Format("Not enough replica available for query at consistency {0} ({1} required but only {2} alive)", consistency, required, alive)) { this.Consistency = consistency; this.RequiredReplicas = required; this.AliveReplicas = alive; }
public UnavailableException(string message, ConsistencyLevel consistencyLevel, int required, int alive) : base(ErrorCodes.Unavailable, message) { ConsistencyLevel = consistencyLevel; Required = required; Alive = alive; }
public IKeyspace Create( ICassandraClient client, string keyspaceName, IDictionary<string, Dictionary<string, string>> keyspaceDesc, ConsistencyLevel consistencyLevel, FailoverPolicy failoverPolicy, IKeyedObjectPool<Endpoint, ICassandraClient> pool) { switch (client.Version) { case CassandraVersion.v0_6_0_beta_3: throw new NotImplementedException("Version 0.6.0 not implimented yet"); default: case CassandraVersion.v0_5_1: return new _051.Keyspace( client, keyspaceName, keyspaceDesc, consistencyLevel, failoverPolicy, pool, monitor ); } }
public IAsyncResult BeginExecuteQuery(int _streamId, byte[] Id, string cql, RowSetMetadata Metadata, object[] values, AsyncCallback callback, object state, object owner, ConsistencyLevel consistency, bool isTracing) { var jar = SetupJob(_streamId, callback, state, owner, "EXECUTE"); BeginJob(jar, SetupKeyspace(jar, SetupPreparedQuery(jar, Id, cql, () => { Evaluate(new ExecuteRequest(jar.StreamId, Id, Metadata, values, consistency, isTracing), jar.StreamId, new Action<ResponseFrame>((frame2) => { var response = FrameParser.Parse(frame2); if (response is ResultResponse) JobFinished(jar, (response as ResultResponse).Output); else _protocolErrorHandlerAction(new ErrorActionParam() { AbstractResponse = response, Jar = jar }); })); }))); return jar; }
public Action GetInsertAction(ISession session, object bindableStatement, ConsistencyLevel consistency, int rowsPerId) { Action action = () => { Trace.TraceInformation("Starting inserting from thread {0}", Thread.CurrentThread.ManagedThreadId); var id = Guid.NewGuid(); for (var i = 0; i < rowsPerId; i++) { var paramsArray = new object[] { id, DateTime.Now, DateTime.Now.ToString() }; IStatement statement = null; if (bindableStatement is SimpleStatement) { statement = ((SimpleStatement)bindableStatement).Bind(paramsArray).SetConsistencyLevel(consistency); } else if (bindableStatement is PreparedStatement) { statement = ((PreparedStatement)bindableStatement).Bind(paramsArray).SetConsistencyLevel(consistency); } else { throw new Exception("Can not bind a statement of type " + bindableStatement.GetType().FullName); } session.Execute(statement); } Trace.TraceInformation("Finished inserting from thread {0}", Thread.CurrentThread.ManagedThreadId); }; return action; }
public QueryTimeoutException(string message, ConsistencyLevel consistencyLevel, int received, int required) : base(message) { ConsistencyLevel = consistencyLevel; ReceivedAcknowledgements = received; RequiredAcknowledgements = required; }
public Task<IEnumerable<object>> Execute(ConsistencyLevel cl, IDataMapperFactory factory) { Action<IFrameWriter> writer = fw => WriteExecuteRequest(fw, cl, factory); Func<IFrameReader, IEnumerable<object>> reader = fr => CQLCommandHelpers.ReadRowSet(fr, factory); return _connection.Execute(writer, reader); }
internal QueryProtocolOptions(ConsistencyLevel consistency, object[] values, bool skipMetadata, int pageSize, byte[] pagingState, ConsistencyLevel serialConsistency) { Consistency = consistency; Values = values; _skipMetadata = skipMetadata; if (pageSize <= 0) { PageSize = QueryOptions.DefaultPageSize; } else if (pageSize == int.MaxValue) { PageSize = -1; } else { PageSize = pageSize; } PagingState = pagingState; SerialConsistency = serialConsistency; }
public Task<IEnumerable<object>> Execute(ConsistencyLevel cl, IDataMapperFactory factory) { IConnection connection; if (null == (connection = _connection)) { lock (_lock) { if (null == (connection = _connection)) { connection = _cluster.GetConnection(null); connection.OnFailure += ConnectionOnOnFailure; Action<IFrameWriter> writer = fw => CQLCommandHelpers.WritePrepareRequest(fw, _cql); Func<IFrameReader, IEnumerable<object>> reader = fr => CQLCommandHelpers.ReadPreparedQuery(fr, connection); connection.Execute(writer, reader).ContinueWith(ReadPreparedQueryInfo).Wait(); Thread.MemoryBarrier(); _connection = connection; } } } Action<IFrameWriter> execWriter = fw => WriteExecuteRequest(fw, cl, factory); Func<IFrameReader, IEnumerable<object>> execReader = fr => CQLCommandHelpers.ReadRowSet(fr, factory); return connection.Execute(execWriter, execReader); }
public Task<IEnumerable<object>> Execute(IDataMapperFactory factory, ConsistencyLevel cl) { IConnection connection; if (null == (connection = _connection)) { lock (_lock) { if (null == (connection = _connection)) { connection = _cluster.GetConnection(null); connection.OnFailure += ConnectionOnOnFailure; Action<IFrameWriter> writer = fw => CQLCommandHelpers.WritePrepareRequest(fw, _cql); Func<IFrameReader, IEnumerable<object>> reader = fr => CQLCommandHelpers.ReadPreparedQuery(fr, connection); InstrumentationToken prepareToken = InstrumentationToken.Create(RequestType.Prepare, _executionFlags, _cql); connection.Execute(writer, reader, _executionFlags, prepareToken).ContinueWith(ReadPreparedQueryInfo).Wait(); _connection = connection; } } } Action<IFrameWriter> execWriter = fw => WriteExecuteRequest(fw, cl, factory); Func<IFrameReader, IEnumerable<object>> execReader = fr => CQLCommandHelpers.ReadRowSet(fr, factory); InstrumentationToken queryToken = InstrumentationToken.Create(RequestType.Query, _executionFlags, _cql); return connection.Execute(execWriter, execReader, _executionFlags, queryToken); }
protected TimeOutException(ErrorCodes code, string message, ConsistencyLevel consistencyLevel, int received, int blockFor) : base(code, message) { ConsistencyLevel = consistencyLevel; Received = received; BlockFor = blockFor; }
public static void RegisterComponents() { var container = new UnityContainer(); var documentUri = ConfigurationManager.AppSettings["DocumentUri"]; string authKey = ConfigurationManager.AppSettings["AuthorizationKey"]; string redisConnection = ConfigurationManager.AppSettings["RedisConnection"]; // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); Uri uri = new Uri(documentUri); ConnectionPolicy connectionPolicy = new ConnectionPolicy() { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }; ConsistencyLevel consistencyLevel = new ConsistencyLevel(); consistencyLevel = ConsistencyLevel.Session; container.RegisterType<IApplicationUserStore, ApplicatonUserStore>(); container.RegisterType<DocumentClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(uri, authKey, connectionPolicy, consistencyLevel)); ConnectionMultiplexer connectionMulp = ConnectionMultiplexer.Connect(redisConnection); container.RegisterInstance<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(redisConnection)); container.RegisterType<IRedisRepository, RedisRepository>(); container.RegisterType<IUserRepository, UserRepository>(); var repo = container.Resolve<IRedisRepository>(); container.RegisterType<RefreshTokenProvider>(new InjectionConstructor(repo)); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); }
public QueryRequest(int streamId, string cqlQuery, ConsistencyLevel consistency, bool tracingEnabled) { this._streamId = streamId; this._cqlQuery = cqlQuery; this._consistency = consistency; if (tracingEnabled) this._flags = 0x02; }
public static void Reset() { ColumnWidth = 40; Formatter = OutputFormatter.Tab; DebugLog = false; Tracing = false; CL = ConsistencyLevel.QUORUM; }
/// <inheritdoc /> protected Statement(QueryProtocolOptions queryProtocolOptions) { _pagingState = queryProtocolOptions.PagingState; _values = queryProtocolOptions.Values; _consistency = queryProtocolOptions.Consistency; _pageSize = queryProtocolOptions.PageSize; _serialConsistency = queryProtocolOptions.SerialConsistency; }
/// Coordinator management/count public static void addCoordinator(IPAddress coordinator, ConsistencyLevel cl) { if (!coordinators.ContainsKey(coordinator)) coordinators.Add(coordinator, 0); var n = coordinators[coordinator]; coordinators[coordinator] = n + 1; achievedConsistencies.Add(cl); }
/// Coordinator management/count public void AddCoordinator(string coordinator, ConsistencyLevel consistencyLevel) { if (!Coordinators.ContainsKey(coordinator)) Coordinators.Add(coordinator, 0); int n = Coordinators[coordinator]; Coordinators[coordinator] = n + 1; AchievedConsistencies.Add(consistencyLevel); }
internal static IObservable<object> CreateQuery(IConnection connection, string cql, ConsistencyLevel cl, IDataMapperFactory factory, ExecutionFlags executionFlags) { Action<IFrameWriter> writer = fw => WriteQueryRequest(fw, cql, cl, MessageOpcodes.Query); Func<IFrameReader, IEnumerable<object>> reader = fr => ReadRowSet(fr, factory); InstrumentationToken token = InstrumentationToken.Create(RequestType.Query, executionFlags, cql); Query query = new Query(writer, reader, token, connection); return query; }
public WriteTimeoutException(ConsistencyLevel consistency, int received, int required, string writeType) : base(string.Format("Cassandra timeout during write query at consitency {0} ({1} replica acknowledged the write over {2} required)", consistency.ToString().ToUpper(), received, required), consistency, received, required) { this.WriteType = writeType; }
internal static void ExecuteSyncQuery(ISession session, string query, ConsistencyLevel consistency, List<object[]> expectedValues = null, string messageInstead = null) { var ret = session.Execute(query, consistency); if (expectedValues != null) { valueComparator(ret, expectedValues); } }
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)."); }
internal static void ExecuteSyncNonQuery(Session session, string query, string messageInstead = null, ConsistencyLevel consistency = ConsistencyLevel.Default) { if (messageInstead != null) Console.WriteLine("CQL<\t" + messageInstead); else Console.WriteLine("CQL< Query:\t" + query); var ret = session.Execute(query, consistency); Console.WriteLine("CQL> (OK)."); }
internal static IObservable<object> CreateExecuteQuery(IConnection connection, byte[] id, IColumnSpec[] columnSpecs, ConsistencyLevel cl, ExecutionFlags executionFlags, string cql, IDataMapperFactory factory) { Action<IFrameWriter> writer = fw => WriteExecuteRequest(fw, id, columnSpecs, cl, factory); Func<IFrameReader, IEnumerable<object>> reader = fr => ReadRowSet(fr, factory); InstrumentationToken token = InstrumentationToken.Create(RequestType.Prepare, executionFlags, cql); Query query = new Query(writer, reader, token, connection); return query; }
public ReadFailureException(ConsistencyLevel consistency, int received, int required, bool dataPresent, int failures) : base(string.Format("Cassandra failure during read query at consistency {0} ({1})", consistency, FormatDetails(received, required, dataPresent))) { ConsistencyLevel = consistency; ReceivedAcknowledgements = received; RequiredAcknowledgements = required; WasDataRetrieved = dataPresent; Failures = failures; }
/// <summary> /// Defines whether to retry and at which consistency level on a read timeout. /// <p> This method triggers a maximum of one retry, and only if enough replica /// had responded to the read request but data was not retrieved amongst those. /// Indeed, that case usually means that enough replica are alive to satisfy the /// consistency but the coordinator picked a dead one for data retrieval, not /// having detecte that replica as dead yet. The reasoning for retrying then is /// that by the time we get the timeout the dead replica will likely have been /// detected as dead and the retry has a high change of success.</p> /// </summary> /// <param name="query"> the original query that timeouted. </param> /// <param name="cl"> the original consistency level of the read that timeouted. /// </param> /// <param name="requiredResponses"> the number of responses that were required /// to achieve the requested consistency level. </param> /// <param name="receivedResponses"> the number of responses that had been /// received by the time the timeout exception was raised. </param> /// <param name="dataRetrieved"> whether actual data (by opposition to data /// checksum) was present in the received responses. </param> /// <param name="nbRetry"> the number of retry already performed for this /// operation. </param> /// /// <returns><code>RetryDecision.retry(cl)</code> if no retry attempt has yet /// been tried and <code>receivedResponses >= requiredResponses && /// !dataRetrieved</code>, <code>RetryDecision.rethrow()</code> /// otherwise.</returns> public RetryDecision OnReadTimeout(Query query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { if (nbRetry != 0) return RetryDecision.Rethrow(); return receivedResponses >= requiredResponses && !dataRetrieved ? RetryDecision.Retry(cl) : RetryDecision.Rethrow(); }
public ExecuteRequest(int streamId, byte[] id, RowSetMetadata metadata, object[] values, ConsistencyLevel consistency, bool tracingEnabled) { this._streamId = streamId; this._values = values; this._id = id; this._metadata = metadata; this._consistency = consistency; if (tracingEnabled) this._flags = 0x02; }
public ReadTimeoutException(ConsistencyLevel consistency, int received, int required, bool dataPresent) : base(string.Format("Cassandra timeout during read query at consistency {0} ({1})", consistency, FormatDetails(received, required, dataPresent)), consistency, received, required) { this.WasDataRetrieved = dataPresent; }
public RetryDecision onWriteTimeout(Query query, ConsistencyLevel cl, String writeType, int requiredAcks, int receivedAcks, int nbRetry) { int hour = DateTime.Now.Hour; if (hour >= nonRetryStartHour && hour <= nonRetryEndHour) { return RetryDecision.Rethrow(); } return policy.OnWriteTimeout(query, cl, writeType, requiredAcks, receivedAcks, nbRetry); }
public RetryDecision onUnavailable(Query query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { int hour = DateTime.Now.Hour; if (hour >= nonRetryStartHour && hour <= nonRetryEndHour) { return RetryDecision.Rethrow(); } return policy.OnUnavailable(query, cl, requiredReplica, aliveReplica, nbRetry); }
protected override void Load(BEBinaryReader reader) { _consistencyLevel = (ConsistencyLevel) reader.ReadInt16(); _received = reader.ReadInt32(); _blockFor = reader.ReadInt32(); if (_isFailure) { _failures = reader.ReadInt32(); } _writeType = reader.ReadString(); }
/// <inheritdoc /> public RowSet Execute(string cqlQuery, ConsistencyLevel consistency) { return(Execute(new SimpleStatement(cqlQuery).SetConsistencyLevel(consistency).SetPageSize(Configuration.QueryOptions.GetPageSize()))); }
public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { Interlocked.Increment(ref UnavailableCounter); return(RetryDecision.Rethrow()); }
/// <inheritdoc /> public RetryDecision OnReadTimeout(IStatement stmt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { return(ChildPolicy.OnReadTimeout(stmt, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry)); }
public async Task GivenAFeedRequest_WithAStrongerConsistencyLevelThanTheDefault_ThenABadRequestExceptionIsThrown(ConsistencyLevel defaultConsistencyLevel, ConsistencyLevel requestedConsistencyLevel) { _innerClient.ConsistencyLevel.Returns(defaultConsistencyLevel); _requestHeaders.Add(CosmosDbConsistencyHeaders.ConsistencyLevel, requestedConsistencyLevel.ToString()); await Assert.ThrowsAsync <BadRequestException>(() => _consistentClient.ReadDatabaseFeedAsync()); }
public new CqlCommand SetSerialConsistencyLevel(ConsistencyLevel consistencyLevel) { base.SetSerialConsistencyLevel(consistencyLevel); return(this); }
public Batch UseConsistencyLevel(ConsistencyLevel consistencyLevel) { this.SetConsistencyLevel(consistencyLevel); return(this); }
internal abstract DocumentClient CreateDocumentClient( Uri hostUri, string key, JsonSerializerSettings settings, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel);
/// <summary> /// Defines whether to retry and at which consistency level on an unavailable /// exception. /// </summary> /// <param name="query"> the original query for which the consistency level /// cannot be achieved. </param> /// <param name="cl"> the original consistency level for the operation. </param> /// <param name="requiredReplica"> the number of replica that should have been /// (known) alive for the operation to be attempted. </param> /// <param name="aliveReplica"> the number of replica that were know to be alive /// by the coordinator of the operation. </param> /// <param name="nbRetry"> the number of retry already performed for this /// operation. </param> /// /// <returns><c>RetryDecision.rethrow()</c>.</returns> public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { return(RetryDecision.Rethrow()); }
/// <summary> /// Defines whether to retry and at which consistency level on a write timeout. /// </summary> /// <param name="query"> the original query that timeouted. </param> /// <param name="cl"> the original consistency level of the write that timeouted. /// </param> /// <param name="writeType"> the type of the write that timeouted. </param> /// <param name="requiredAcks"> the number of acknowledgments that were required /// to achieve the requested consistency level. </param> /// <param name="receivedAcks"> the number of acknowledgments that had been /// received by the time the timeout exception was raised. </param> /// <param name="nbRetry"> the number of retry already performed for this /// operation. </param> /// /// <returns><c>RetryDecision.rethrow()</c>.</returns> public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry) { return(RetryDecision.Rethrow()); }
// We don't want to expose the constructor, because the code rely on this being only subclassed by Statement and BoundStatement protected Query() { this._consistency = ConsistencyLevel.Default; }
/// <inheritdoc /> public IAsyncResult BeginExecute(string cqlQuery, ConsistencyLevel consistency, AsyncCallback callback, object state) { return(BeginExecute(new SimpleStatement(cqlQuery).SetConsistencyLevel(consistency), callback, state)); }
private static ConsistencyLevel CL(ConsistencyLevel cl, RetryDecision decision) { return(decision.RetryConsistencyLevel ?? cl); }
public void TestStoredProcedure() { // Create a document client with a customer json serializer settings JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); serializerSettings.Converters.Add(new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_))); ConnectionPolicy connectionPolicy = new ConnectionPolicy { ConnectionMode = ConnectionMode.Gateway }; ConsistencyLevel defaultConsistencyLevel = ConsistencyLevel.Session; DocumentClient client = CreateDocumentClient( this.hostUri, this.masterKey, serializerSettings, connectionPolicy, defaultConsistencyLevel); // Create a simple stored procedure var scriptId = "bulkImportScript"; var sproc = new StoredProcedure { Id = scriptId, Body = @" function bulkImport(docs) { var collection = getContext().getCollection(); var collectionLink = collection.getSelfLink(); // The count of imported docs, also used as current doc index. var count = 0; // Validate input. if (!docs) throw new Error(""The array is undefined or null.""); var docsLength = docs.length; if (docsLength == 0) { getContext().getResponse().setBody(0); } // Call the CRUD API to create a document. tryCreate(docs[count], callback); // Note that there are 2 exit conditions: // 1) The createDocument request was not accepted. // In this case the callback will not be called, we just call setBody and we are done. // 2) The callback was called docs.length times. // In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done. function tryCreate(doc, callback) { // If you are sure that every document will contain its own (unique) id field then // disable the option to auto generate ids. // by leaving this on, the entire document is parsed to check if there is an id field or not // by disabling this, parsing of the document is skipped because you're telling DocumentDB // that you are providing your own ids. // depending on the size of your documents making this change can have a significant // improvement on document creation. var options = { disableAutomaticIdGeneration: true }; var isAccepted = collection.createDocument(collectionLink, doc, options, callback); // If the request was accepted, callback will be called. // Otherwise report current count back to the client, // which will call the script again with remaining set of docs. // This condition will happen when this stored procedure has been running too long // and is about to get cancelled by the server. This will allow the calling client // to resume this batch from the point we got to before isAccepted was set to false if (!isAccepted) getContext().getResponse().setBody(count); } // This is called when collection.createDocument is done and the document has been persisted. function callback(err, doc, options) { if (err) throw err; // One more document has been inserted, increment the count. count++; if (count >= docsLength) { // If we have created all documents, we are done. Just set the response. getContext().getResponse().setBody(count); } else { // Create next document. tryCreate(docs[count], callback); } } } " }; sproc = client.CreateStoredProcedureAsync(collectionUri, sproc).Result.Resource; var doc = new MyObject(1); var args = new dynamic[] { new dynamic[] { doc } }; RequestOptions requestOptions = ApplyRequestOptions(new RequestOptions { PartitionKey = new PartitionKey("value") }, serializerSettings); StoredProcedureResponse <int> scriptResult = client.ExecuteStoredProcedureAsync <int>( sproc.SelfLink, requestOptions, args).Result; var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.id); var readDoc = client.ReadDocumentAsync <MyObject>(docUri, requestOptions).Result.Document; Assert.IsNotNull(readDoc.SerializedObject); Assert.AreEqual(doc.SerializedObject.Name, readDoc.SerializedObject.Name); }
public void SaveChangesOneByOne(Context context, string tablename, ConsistencyLevel consistencyLevel) { var commitActions = new List <Action>(); try { foreach (KeyValuePair <TEntity, TableEntry> kv in _table) { if (!CqlEqualityComparer <TEntity> .Default.Equals(kv.Key, kv.Value.Entity)) { throw new InvalidOperationException(); } string cql = ""; object[] values; if (kv.Value.MutationType == MutationType.Add) { cql = CqlQueryTools.GetInsertCQLAndValues(kv.Value.Entity, tablename, out values, null, null, false); } else if (kv.Value.MutationType == MutationType.Delete) { cql = CqlQueryTools.GetDeleteCQLAndValues(kv.Value.Entity, tablename, out values); } else if (kv.Value.MutationType == MutationType.None) { cql = CqlQueryTools.GetUpdateCQLAndValues(kv.Key, kv.Value.Entity, tablename, out values, kv.Value.CqlEntityUpdateMode == EntityUpdateMode.AllOrNone); } else { continue; } QueryTrace trace = null; if (cql != null) // null if nothing to update { RowSet res = context.ExecuteWriteQuery(cql, values, consistencyLevel, kv.Value.QueryTracingEnabled); if (kv.Value.QueryTracingEnabled) { trace = res.Info.QueryTrace; } } KeyValuePair <TEntity, TableEntry> nkv = kv; commitActions.Add(() => { if (nkv.Value.QueryTracingEnabled) { if (trace != null) { _traces.TryAdd(nkv.Key, trace); } } _table.Remove(nkv.Key); if (nkv.Value.MutationType != MutationType.Delete && nkv.Value.CqlEntityTrackingMode != EntityTrackingMode.DetachAfterSave) { _table.Add(Clone(nkv.Value.Entity), new TableEntry { Entity = nkv.Value.Entity, MutationType = MutationType.None, CqlEntityUpdateMode = nkv.Value.CqlEntityUpdateMode, CqlEntityTrackingMode = nkv.Value.CqlEntityTrackingMode }); } }); } } finally { foreach (Action act in commitActions) { act(); } } }
private async Task TestOrderyByQueryAsync() { var jsonSerializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, Converters = { new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_)) } }; var connectionPolicy = new ConnectionPolicy(); ConsistencyLevel defaultConsistencyLevel = ConsistencyLevel.Session; DocumentClient client = this.CreateDocumentClient( this.hostUri, this.masterKey, jsonSerializerSettings, connectionPolicy, defaultConsistencyLevel); var collectionUri = UriFactory.CreateDocumentCollectionUri(this.databaseName, this.collectionName); // Create a few test documents int documentCount = 3; var numberFieldName = "NumberField"; for (int i = 0; i < documentCount; ++i) { var newDocument = new MyObject(i); var createdDocument = client.CreateDocumentAsync(collectionUri, newDocument, ApplyRequestOptions(new RequestOptions(), jsonSerializerSettings)).Result.Resource; } FeedOptions feedOptions = this.ApplyFeedOptions( new FeedOptions { EnableCrossPartitionQuery = true, MaxBufferedItemCount = -1, MaxDegreeOfParallelism = -1, MaxItemCount = -1 }, jsonSerializerSettings); var orderedQuery = client.CreateDocumentQuery <MyObject>( collectionUri, new SqlQuerySpec( "SELECT * FROM root" ), feedOptions); var orderedQuery2 = client.CreateDocumentQuery <MyObject>( collectionUri, new SqlQuerySpec( "SELECT * FROM root ORDER BY root[\"" + numberFieldName + "\"] DESC" ), feedOptions); var documentQuery = orderedQuery.AsDocumentQuery(); var documentQuery2 = orderedQuery2.AsDocumentQuery(); var results = await documentQuery.ExecuteNextAsync <MyObject>(); var results2 = await documentQuery2.ExecuteNextAsync <MyObject>(); var list1 = results.ToList(); var list2 = results2.ToList(); Assert.AreEqual(documentCount, list1.Count); Assert.AreEqual(documentCount, list2.Count); for (int i = 0; i < documentCount; ++i) { Assert.AreEqual("Name: " + (documentCount - i - 1), list2[i].SerializedObject.Name); } }
/// <summary> /// Returns true if the ConsistencyLevel is either <see cref="ConsistencyLevel.Serial"/> or <see cref="ConsistencyLevel.LocalSerial"/>, /// otherwise false. /// </summary> public static bool IsSerialConsistencyLevel(this ConsistencyLevel consistency) { return(consistency == ConsistencyLevel.Serial || consistency == ConsistencyLevel.LocalSerial); }
/// <summary> /// Sets a default consistency level for all <c>BoundStatement</c> created /// from this object. <p> If no consistency level is set through this method, the /// BoundStatement created from this object will use the default consistency /// level (One). </p><p> Changing the default consistency level is not retroactive, /// it only applies to BoundStatement created after the change.</p> /// </summary> /// <param name="consistency"> the default consistency level to set. </param> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetConsistencyLevel(ConsistencyLevel consistency) { ConsistencyLevel = consistency; return(this); }
internal static void ExecuteSyncQuery(Session session, string query, List <object[]> expectedValues = null, ConsistencyLevel consistency = ConsistencyLevel.Default, string messageInstead = null) { if (messageInstead != null) { Console.WriteLine("CQL<\t" + messageInstead); } else { Console.WriteLine("CQL< Query:\t" + query); } if (expectedValues != null) { using (var ret = session.Execute(query, consistency)) valueComparator(ret, expectedValues); } using (var ret = session.Execute(query, consistency)) ret.PrintTo(stream: Console.Out, cellEncoder: CellEncoder); Console.WriteLine("CQL> Done."); }
public new CqlConditionalCommand <TEntity> SetSerialConsistencyLevel(ConsistencyLevel consistencyLevel) { base.SetSerialConsistencyLevel(consistencyLevel); return(this); }
/// <inheritdoc /> public RetryDecision OnUnavailable(IStatement stmt, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { return(ChildPolicy.OnUnavailable(stmt, cl, requiredReplica, aliveReplica, nbRetry)); }
internal static IPAddress 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"); } var ret = session.Execute(prepared.Bind(values).SetConsistencyLevel(consistency)); Console.WriteLine("CQL> (OK)."); return(ret.Info.QueriedHost); }
public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry) { WriteTimeoutCounter++; return(RetryDecision.Ignore()); }
public IPropertyBagCommand WithConsistencyLevel(ConsistencyLevel cl) { _command.WithConsistencyLevel(cl); return(this); }
public RetryDecision OnUnavailable(IStatement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { UnavailableCounter++; return(RetryDecision.Ignore()); }
public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { Interlocked.Increment(ref ReadTimeoutCounter); return(RetryDecision.Rethrow()); }
public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { ReadTimeoutCounter++; return(RetryDecision.Ignore()); }
public RetryDecision OnWriteTimeout(IStatement query, ConsistencyLevel cl, string writeType, int requiredAcks, int receivedAcks, int nbRetry) { Interlocked.Increment(ref WriteTimeoutCounter); return(RetryDecision.Rethrow()); }
public static Apache.Cassandra.ConsistencyLevel ToThrift(this ConsistencyLevel level) { return((Apache.Cassandra.ConsistencyLevel)level); }
/// <summary> /// Sets the consistency level for the query. <p> The default consistency level, /// if this method is not called, is ConsistencyLevel.ONE.</p> /// </summary> /// <param name="consistency"> the consistency level to set. </param> /// /// <returns>this <code>Query</code> object.</returns> public Query SetConsistencyLevel(ConsistencyLevel consistency) { this._consistency = consistency; return(this); }
/// <summary> /// Defines whether to retry and at which consistency level on a read timeout. /// </summary> /// <param name="query"> the original query that timeouted. </param> /// <param name="cl"> the original consistency level of the read that timeouted. /// </param> /// <param name="requiredResponses"> the number of responses that were required /// to achieve the requested consistency level. </param> /// <param name="receivedResponses"> the number of responses that had been /// received by the time the timeout exception was raised. </param> /// <param name="dataRetrieved"> whether actual data (by opposition to data /// checksum) was present in the received responses. </param> /// <param name="nbRetry"> the number of retry already performed for this /// operation. </param> /// /// <returns><c>RetryDecision.rethrow()</c>.</returns> public RetryDecision OnReadTimeout(IStatement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, bool dataRetrieved, int nbRetry) { return(RetryDecision.Rethrow()); }