Class StatementWrapper
- java.lang.Object
-
- com.datastax.driver.core.Statement
-
- com.datastax.driver.core.StatementWrapper
-
public abstract class StatementWrapper extends Statement
Base class for customStatementimplementations that wrap another statement.This is intended for use with a custom
RetryPolicy,LoadBalancingPolicyorSpeculativeExecutionPolicy. The client code can wrap a statement to "mark" it, or add information that will lead to special handling in the policy.Example:
// Define your own subclass public class MyCustomStatement extends StatementWrapper { public MyCustomStatement(Statement wrapped) { super(wrapped); } } // In your load balancing policy, add a special case for that new type public class MyLoadBalancingPolicy implements LoadBalancingPolicy { public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { if (statement instanceof MyCustomStatement) { // return specially crafted plan } else { // return default plan } } } // The client wraps whenever it wants to trigger the special plan Statement s = new SimpleStatement("..."); session.execute(s); // will use default plan session.execute(new MyCustomStatement(s)); // will use special plan
-
-
Field Summary
-
Fields inherited from class com.datastax.driver.core.Statement
idempotent, NULL_PAYLOAD_VALUE
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedStatementWrapper(Statement wrapped)Builds a new instance.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description StatementdisableTracing()Disables tracing for this query.StatementenableTracing()Enables tracing for this query.ConsistencyLevelgetConsistencyLevel()The consistency level for this query.longgetDefaultTimestamp()The default timestamp for this query.intgetFetchSize()The fetch size for this query.HostgetHost()StringgetKeyspace()Returns the keyspace this query operates on.intgetNowInSeconds()Map<String,ByteBuffer>getOutgoingPayload()Returns this statement's outgoing payload.ByteBuffergetPagingState()intgetReadTimeoutMillis()Return the per-host read timeout that was set for this statement.RetryPolicygetRetryPolicy()Returns the retry policy sets for this query, if any.ByteBuffergetRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry)Returns the routing key (in binary raw form) to use for token aware routing of this query.ConsistencyLevelgetSerialConsistencyLevel()The serial consistency level for this query.BooleanisIdempotent()Whether this statement is idempotent, i.e. whether it can be applied multiple times without changing the result beyond the initial application.booleanisIdempotentWithDefault(QueryOptions queryOptions)booleanisTracing()Returns whether tracing is enabled for this query or not.intrequestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry codecRegistry)Returns the number of bytes required to encode this statement.StatementsetConsistencyLevel(ConsistencyLevel consistency)Sets the consistency level for the query.StatementsetDefaultTimestamp(long defaultTimestamp)Sets the default timestamp for this query (in microseconds since the epoch).StatementsetFetchSize(int fetchSize)Sets the query fetch size.StatementsetHost(Host host)Sets theHostthat should handle this query.StatementsetIdempotent(boolean idempotent)Sets whether this statement is idempotent.StatementsetNowInSeconds(int nowInSeconds)Sets the "now in seconds" to use when applying the request (for testing purposes).StatementsetOutgoingPayload(Map<String,ByteBuffer> payload)Set the given outgoing payload on this statement.StatementsetPagingState(PagingState pagingState)Sets the paging state.StatementsetPagingState(PagingState pagingState, CodecRegistry codecRegistry)Sets the paging state.StatementsetPagingStateUnsafe(byte[] pagingState)Sets the paging state.StatementsetReadTimeoutMillis(int readTimeoutMillis)Overrides the default per-host read timeout (SocketOptions.getReadTimeoutMillis()) for this statement.StatementsetRetryPolicy(RetryPolicy policy)Sets the retry policy to use for this query.StatementsetSerialConsistencyLevel(ConsistencyLevel serialConsistency)Sets the serial consistency level for the query.-
Methods inherited from class com.datastax.driver.core.Statement
getLastHost, getPartitioner, isBatchIdempotent, isLWT, setLastHost
-
-
-
-
Constructor Detail
-
StatementWrapper
protected StatementWrapper(Statement wrapped)
Builds a new instance.- Parameters:
wrapped- the wrapped statement.
-
-
Method Detail
-
setConsistencyLevel
public Statement setConsistencyLevel(ConsistencyLevel consistency)
Description copied from class:StatementSets the consistency level for the query.- Overrides:
setConsistencyLevelin classStatement- Parameters:
consistency- the consistency level to set.- Returns:
- this
Statementobject.
-
getConsistencyLevel
public ConsistencyLevel getConsistencyLevel()
Description copied from class:StatementThe consistency level for this query.- Overrides:
getConsistencyLevelin classStatement- Returns:
- the consistency level for this query, or
nullif no consistency level has been specified (throughsetConsistencyLevel). In the latter case, the default consistency level will be used.
-
setSerialConsistencyLevel
public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency)
Description copied from class:StatementSets the serial consistency level for the query.The serial consistency level is only used by conditional updates (
INSERT,UPDATEorDELETEstatements with anIFcondition). For those, the serial consistency level defines the consistency level of the serial phase (or "paxos" phase) while the normal consistency level defines the consistency for the "learn" phase, i.e. what type of reads will be guaranteed to see the update right away. For instance, if a conditional write has a regular consistency of QUORUM (and is successful), then a QUORUM read is guaranteed to see that write. But if the regular consistency of that write is ANY, then only a read with a consistency of SERIAL is guaranteed to see it (even a read with consistency ALL is not guaranteed to be enough).The serial consistency can only be one of
ConsistencyLevel.SERIALorConsistencyLevel.LOCAL_SERIAL. WhileConsistencyLevel.SERIALguarantees full linearizability (with other SERIAL updates),ConsistencyLevel.LOCAL_SERIALonly guarantees it in the local data center.The serial consistency level is ignored for any query that is not a conditional update (serial reads should use the regular consistency level for instance).
- Overrides:
setSerialConsistencyLevelin classStatement- Parameters:
serialConsistency- the serial consistency level to set.- Returns:
- this
Statementobject.
-
getSerialConsistencyLevel
public ConsistencyLevel getSerialConsistencyLevel()
Description copied from class:StatementThe serial consistency level for this query.See
Statement.setSerialConsistencyLevel(ConsistencyLevel)for more detail on the serial consistency level.- Overrides:
getSerialConsistencyLevelin classStatement- Returns:
- the serial consistency level for this query, or
nullif no serial consistency level has been specified (throughStatement.setSerialConsistencyLevel(ConsistencyLevel)). In the latter case, the default serial consistency level will be used.
-
enableTracing
public Statement enableTracing()
Description copied from class:StatementEnables tracing for this query.By default (that is unless you call this method), tracing is not enabled.
- Overrides:
enableTracingin classStatement- Returns:
- this
Statementobject.
-
disableTracing
public Statement disableTracing()
Description copied from class:StatementDisables tracing for this query.- Overrides:
disableTracingin classStatement- Returns:
- this
Statementobject.
-
isTracing
public boolean isTracing()
Description copied from class:StatementReturns whether tracing is enabled for this query or not.
-
getRoutingKey
public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry)
Description copied from class:StatementReturns the routing key (in binary raw form) to use for token aware routing of this query.The routing key is optional in that implementers are free to return
null. The routing key is an hint used for token-aware routing (seeTokenAwarePolicy), and if provided should correspond to the binary value for the query partition key. However, not providing a routing key never causes a query to fail and if the load balancing policy used is not token aware, then the routing key can be safely ignored.- Specified by:
getRoutingKeyin classStatement- Parameters:
protocolVersion- the protocol version that will be used if the actual implementation needs to serialize something to compute the key.codecRegistry- the codec registry that will be used if the actual implementation needs to serialize something to compute this key.- Returns:
- the routing key for this query or
null.
-
getKeyspace
public String getKeyspace()
Description copied from class:StatementReturns the keyspace this query operates on.Note that not all query specify on which keyspace they operate on, and so this method can always return
null. Firstly, some queries do not operate inside a keyspace: keyspace creation,USEqueries, user creation, etc. Secondly, even query that operate within a keyspace do not have to specify said keyspace directly, in which case the currently logged in keyspace (the one set through aUSEquery (or through the use ofCluster.connect(String))). Lastly, as for the routing key, this keyspace information is only a hint for token-aware routing (since replica placement depend on the replication strategy in use which is a per-keyspace property) and having this method returnnull(or even a bogus keyspace name) will never cause the query to fail.- Specified by:
getKeyspacein classStatement- Returns:
- the keyspace this query operate on if relevant or
null.
-
setRetryPolicy
public Statement setRetryPolicy(RetryPolicy policy)
Description copied from class:StatementSets the retry policy to use for this query.The default retry policy, if this method is not called, is the one returned by
Policies.getRetryPolicy()in the cluster configuration. This method is thus only useful in case you want to punctually override the default policy for this request.- Overrides:
setRetryPolicyin classStatement- Parameters:
policy- the retry policy to use for this query.- Returns:
- this
Statementobject.
-
getRetryPolicy
public RetryPolicy getRetryPolicy()
Description copied from class:StatementReturns the retry policy sets for this query, if any.- Overrides:
getRetryPolicyin classStatement- Returns:
- the retry policy sets specifically for this query or
nullif no query specific retry policy has been set throughStatement.setRetryPolicy(com.datastax.driver.core.policies.RetryPolicy)(in which case the Cluster retry policy will apply if necessary).
-
setFetchSize
public Statement setFetchSize(int fetchSize)
Description copied from class:StatementSets the query fetch size.The fetch size controls how much resulting rows will be retrieved simultaneously (the goal being to avoid loading too much results in memory for queries yielding large results). Please note that while value as low as 1 can be used, it is *highly* discouraged to use such a low value in practice as it will yield very poor performance. If in doubt, leaving the default is probably a good idea.
Only
SELECTqueries only ever make use of this setting.Note that unlike other configuration, when this statement is prepared
BoundStatements created off ofPreparedStatementdo not inherit this configuration.Note: Paging is not supported with the native protocol version 1. If you call this method with
fetchSize > 0andfetchSize != Integer.MAX_VALUEand the protocol version is in use (i.e. if you've force version 1 throughCluster.Builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion)or you use Cassandra 1.2), you will getUnsupportedProtocolVersionExceptionwhen submitting this statement for execution.- Overrides:
setFetchSizein classStatement- Parameters:
fetchSize- the fetch size to use. IffetchSize <e; 0, the default fetch size will be used. To disable paging of the result set, usefetchSize == Integer.MAX_VALUE.- Returns:
- this
Statementobject.
-
getFetchSize
public int getFetchSize()
Description copied from class:StatementThe fetch size for this query.- Overrides:
getFetchSizein classStatement- Returns:
- the fetch size for this query. If that value is less or equal to 0 (the default unless
Statement.setFetchSize(int)is used), the default fetch size will be used.
-
setDefaultTimestamp
public Statement setDefaultTimestamp(long defaultTimestamp)
Description copied from class:StatementSets the default timestamp for this query (in microseconds since the epoch).This feature is only available when version
V3or higher of the native protocol is in use. With earlier versions, calling this method has no effect.The actual timestamp that will be used for this query is, in order of preference:
- the timestamp specified directly in the CQL query string (using the
USING TIMESTAMPsyntax); - the timestamp specified through this method, if different from
Long.MIN_VALUE; - the timestamp returned by the
TimestampGeneratorcurrently in use, if different fromLong.MIN_VALUE.
Note that unlike other configuration, when this statement is prepared
BoundStatements created off ofPreparedStatementdo not inherit this configuration.- Overrides:
setDefaultTimestampin classStatement- Parameters:
defaultTimestamp- the default timestamp for this query (must be strictly positive).- Returns:
- this
Statementobject. - See Also:
Cluster.Builder.withTimestampGenerator(TimestampGenerator)
- the timestamp specified directly in the CQL query string (using the
-
getDefaultTimestamp
public long getDefaultTimestamp()
Description copied from class:StatementThe default timestamp for this query.- Overrides:
getDefaultTimestampin classStatement- Returns:
- the default timestamp (in microseconds since the epoch).
-
setReadTimeoutMillis
public Statement setReadTimeoutMillis(int readTimeoutMillis)
Description copied from class:StatementOverrides the default per-host read timeout (SocketOptions.getReadTimeoutMillis()) for this statement.You should override this only for statements for which the coordinator may allow a longer server-side timeout (for example aggregation queries).
Note that unlike other configuration, when this statement is prepared
BoundStatements created off ofPreparedStatementdo not inherit this configuration.- Overrides:
setReadTimeoutMillisin classStatement- Parameters:
readTimeoutMillis- the timeout to set. Negative values are not allowed. If it is 0, the read timeout will be disabled for this statement.- Returns:
- this
Statementobject.
-
getReadTimeoutMillis
public int getReadTimeoutMillis()
Description copied from class:StatementReturn the per-host read timeout that was set for this statement.- Overrides:
getReadTimeoutMillisin classStatement- Returns:
- the timeout. Note that a negative value means that the default
SocketOptions.getReadTimeoutMillis()will be used.
-
setPagingState
public Statement setPagingState(PagingState pagingState, CodecRegistry codecRegistry)
Description copied from class:StatementSets the paging state.This will cause the next execution of this statement to fetch results from a given page, rather than restarting from the beginning.
You get the paging state from a previous execution of the statement (see
ExecutionInfo.getPagingState(). This is typically used to iterate in a "stateless" manner (e.g. across HTTP requests):Statement st = new SimpleStatement("your query"); ResultSet rs = session.execute(st.setFetchSize(20)); int available = rs.getAvailableWithoutFetching(); for (int i = 0; i < available; i++) { Row row = rs.one(); // Do something with row (e.g. display it to the user...) } // Get state and serialize as string or byte[] to store it for the next execution // (e.g. pass it as a parameter in the "next page" URI) PagingState pagingState = rs.getExecutionInfo().getPagingState(); String savedState = pagingState.toString(); // Next execution: // Get serialized state back (e.g. get URI parameter) String savedState = ... Statement st = new SimpleStatement("your query"); st.setPagingState(PagingState.fromString(savedState)); ResultSet rs = session.execute(st.setFetchSize(20)); int available = rs.getAvailableWithoutFetching(); for (int i = 0; i < available; i++) { ... }The paging state can only be reused between perfectly identical statements (same query string, same bound parameters). Altering the contents of the paging state or trying to set it on a different statement will cause this method to fail.
Note that, due to internal implementation details, the paging state is not portable across native protocol versions (see the online documentation for more explanations about the native protocol). This means that
PagingStateinstances generated with an old version won't work with a higher version. If that is a problem for you, consider using the "unsafe" API (seeStatement.setPagingStateUnsafe(byte[])).- Overrides:
setPagingStatein classStatement- Parameters:
pagingState- the paging state to set, ornullto remove any state that was previously set on this statement.codecRegistry- the codec registry that will be used if this method needs to serialize the statement's values in order to check that the paging state matches.- Returns:
- this
Statementobject. - See Also:
Statement.setPagingState(PagingState)
-
setPagingState
public Statement setPagingState(PagingState pagingState)
Description copied from class:StatementSets the paging state.This method calls
Statement.setPagingState(PagingState, CodecRegistry)withCodecRegistry.DEFAULT_INSTANCE. Whether you should use this or the other variant depends on the type of statement this is called on:- for a
BoundStatement, the codec registry isn't actually needed, so it's always safe to use this method; - for a
SimpleStatementorBuiltStatement, you can use this method if you use no custom codecs, or if your custom codecs are registered with the default registry. Otherwise, use the other method and provide the registry that contains your codecs.
- Overrides:
setPagingStatein classStatement- Parameters:
pagingState- the paging state to set, ornullto remove any state that was previously set on this statement.
- for a
-
setPagingStateUnsafe
public Statement setPagingStateUnsafe(byte[] pagingState)
Description copied from class:StatementSets the paging state.Contrary to
Statement.setPagingState(PagingState), this method takes the "raw" form of the paging state (previously extracted withExecutionInfo.getPagingStateUnsafe(). It won't validate that this statement matches the one that the paging state was extracted from. If the paging state was altered in any way, you will get unpredictable behavior from Cassandra (ranging from wrong results to a query failure). If you decide to use this variant, it is strongly recommended to add your own validation (for example, signing the raw state with a private key).- Overrides:
setPagingStateUnsafein classStatement- Parameters:
pagingState- the paging state to set, ornullto remove any state that was previously set on this statement.- Returns:
- this
Statementobject.
-
getPagingState
public ByteBuffer getPagingState()
-
setIdempotent
public Statement setIdempotent(boolean idempotent)
Description copied from class:StatementSets whether this statement is idempotent.See
Statement.isIdempotent()for more explanations about this property.- Overrides:
setIdempotentin classStatement- Parameters:
idempotent- the new value.- Returns:
- this
Statementobject.
-
isIdempotent
public Boolean isIdempotent()
Description copied from class:StatementWhether this statement is idempotent, i.e. whether it can be applied multiple times without changing the result beyond the initial application.If a statement is not idempotent, the driver will ensure that it never gets executed more than once, which means:
- avoiding
retrieson write timeouts or request errors; - never scheduling
speculative executions.
Note that this method can return
null, in which case the driver will default toQueryOptions.getDefaultIdempotence().By default, this method returns
nullfor all statements, except forBuiltStatement- value will be inferred from the query: if it updates counters, prepends/appends to a list, or uses a function call orQueryBuilder.raw(String)anywhere in an inserted value, the result will befalse; otherwise it will betrue.BatchandBatchStatement:- If any statement in batch has isIdempotent() false - return false
- If no statements with isIdempotent() false, but some have isIdempotent() null - return null
- Otherwise - return true
Statement.setIdempotent(boolean)forces a value that overrides calculated value.Note that when a statement is prepared (
Session.prepare(String)), its idempotence flag will be propagated to allPreparedStatements created from it.- Overrides:
isIdempotentin classStatement- Returns:
- whether this statement is idempotent, or
nullto useQueryOptions.getDefaultIdempotence().
- avoiding
-
isIdempotentWithDefault
public boolean isIdempotentWithDefault(QueryOptions queryOptions)
-
getOutgoingPayload
public Map<String,ByteBuffer> getOutgoingPayload()
Description copied from class:StatementReturns this statement's outgoing payload. Each time this statement is executed, this payload will be included in the query request.This method returns
nullif no payload has been set, otherwise it always returns immutable maps.This feature is only available with
ProtocolVersion.V4or above. Trying to include custom payloads in requests sent by the driver under lower protocol versions will result in anUnsupportedFeatureException(wrapped in aNoHostAvailableException).- Overrides:
getOutgoingPayloadin classStatement- Returns:
- the outgoing payload to include with this statement, or
nullif no payload has been set.
-
setOutgoingPayload
public Statement setOutgoingPayload(Map<String,ByteBuffer> payload)
Description copied from class:StatementSet the given outgoing payload on this statement. Each time this statement is executed, this payload will be included in the query request.This method makes a defensive copy of the given map, but its values remain inherently mutable. Care should be taken not to modify the original map once it is passed to this method.
This feature is only available with
ProtocolVersion.V4or above. Trying to include custom payloads in requests sent by the driver under lower protocol versions will result in anUnsupportedFeatureException(wrapped in aNoHostAvailableException).- Overrides:
setOutgoingPayloadin classStatement- Parameters:
payload- the outgoing payload to include with this statement, ornullto clear any previously entered payload.- Returns:
- this
Statementobject.
-
requestSizeInBytes
public int requestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry codecRegistry)
Description copied from class:StatementReturns the number of bytes required to encode this statement.The calculated size may be overestimated by a few bytes, but is never underestimated. If the size cannot be calculated, this method returns -1.
Note that the returned value is not cached, but instead recomputed at every method call.
- Overrides:
requestSizeInBytesin classStatement- Returns:
- the number of bytes required to encode this statement.
-
getHost
public Host getHost()
- Overrides:
getHostin classStatement- Returns:
- The host configured on this statement, or null if none is configured.
- See Also:
Statement.setHost(Host)
-
setHost
public Statement setHost(Host host)
Description copied from class:StatementSets theHostthat should handle this query.In the general case, use of this method is heavily discouraged and should only be used in the following cases:
- Querying node-local tables, such as tables in the
systemandsystem_viewskeyspaces. - Applying a series of schema changes, where it may be advantageous to execute schema changes in sequence on the same node.
Configuring a specific host causes the configured
LoadBalancingPolicyto be completely bypassed. However, if the load balancing policy dictates that the host is at distanceHostDistance.IGNOREDor there is no active connectivity to the host, the request will fail with aNoHostAvailableException.Note that unlike other configuration, when this statement is prepared
BoundStatements created off ofPreparedStatementdo not inherit this configuration. - Querying node-local tables, such as tables in the
-
getNowInSeconds
public int getNowInSeconds()
- Overrides:
getNowInSecondsin classStatement- Returns:
- a custom "now in seconds" to use when applying the request (for testing purposes).
Integer.MIN_VALUEmeans "no value".
-
setNowInSeconds
public Statement setNowInSeconds(int nowInSeconds)
Description copied from class:StatementSets the "now in seconds" to use when applying the request (for testing purposes).Integer.MIN_VALUEmeans "no value".- Overrides:
setNowInSecondsin classStatement
-
-