Interface Session
-
- All Superinterfaces:
AutoCloseable,Closeable
- All Known Implementing Classes:
AbstractSession
public interface Session extends Closeable
A session holds connections to a Cassandra cluster, allowing it to be queried.Each session maintains multiple connections to the cluster nodes, provides policies to choose which node to use for each query (round-robin on all nodes of the cluster by default), and handles retries for failed queries (when it makes sense), etc...
Session instances are thread-safe and usually a single instance is enough per application. As a given session can only be "logged" into one keyspace at a time (where the "logged" keyspace is the one used by queries that don't explicitly use a fully qualified table name), it can make sense to create one session per keyspace used. This is however not necessary when querying multiple keyspaces since it is always possible to use a single session with fully qualified table names in queries.
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static interfaceSession.StateThe state of a Session.
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description voidclose()Initiates a shutdown of this session instance and blocks until that shutdown completes.CloseFuturecloseAsync()Initiates a shutdown of this session instance.ResultSetexecute(Statement statement)Executes the provided query.ResultSetexecute(String query)Executes the provided query.ResultSetexecute(String query, Object... values)Executes the provided query using the provided values.ResultSetexecute(String query, Map<String,Object> values)Executes the provided query using the provided named values.ResultSetFutureexecuteAsync(Statement statement)Executes the provided query asynchronously.ResultSetFutureexecuteAsync(String query)Executes the provided query asynchronously.ResultSetFutureexecuteAsync(String query, Object... values)Executes the provided query asynchronously using the provided values.ResultSetFutureexecuteAsync(String query, Map<String,Object> values)Executes the provided query asynchronously using the provided values.ClustergetCluster()Returns theClusterobject this session is part of.StringgetLoggedKeyspace()The keyspace to which this Session is currently logged in, if any.Session.StategetState()Return a snapshot of the state of this Session.Sessioninit()Force the initialization of this Session instance if it hasn't been initialized yet.ListenableFuture<Session>initAsync()Initialize this session asynchronously.booleanisClosed()Whether this Session instance has been closed.PreparedStatementprepare(RegularStatement statement)Prepares the provided query.PreparedStatementprepare(String query)Prepares the provided query string.ListenableFuture<PreparedStatement>prepareAsync(RegularStatement statement)Prepares the provided query asynchronously.ListenableFuture<PreparedStatement>prepareAsync(String query)Prepares the provided query string asynchronously.
-
-
-
Method Detail
-
getLoggedKeyspace
String getLoggedKeyspace()
The keyspace to which this Session is currently logged in, if any.This correspond to the name passed to
Cluster.connect(String), or to the last keyspace logged into through a "USE" CQL query if one was used.- Returns:
- the name of the keyspace to which this Session is currently logged in, or
nullif the session is logged to no keyspace.
-
init
Session init()
Force the initialization of this Session instance if it hasn't been initialized yet.Please note first that most users won't need to call this method explicitly. If you use the
Cluster.connect()method to create your Session, the returned session will be already initialized. Even if you create a non-initialized session throughCluster.newSession(), that session will get automatically initialized the first time it is used for querying. This method is thus only useful if you useCluster.newSession()and want to explicitly force initialization without querying.Session initialization consists in connecting the Session to the known Cassandra hosts (at least those that should not be ignored due to the
LoadBalancingPolicyin place).If the Cluster instance this Session depends on is not itself initialized, it will be initialized by this method.
If the session is already initialized, this method is a no-op.
- Returns:
- this
Sessionobject. - Throws:
NoHostAvailableException- if this initialization triggers theClusterinitialization and no host amongst the contact points can be reached.AuthenticationException- if this initialization triggers theClusterinitialization and an authentication error occurs while contacting the initial contact points.
-
initAsync
ListenableFuture<Session> initAsync()
Initialize this session asynchronously.- Returns:
- a future that will complete when the session is fully initialized.
- See Also:
init()
-
execute
ResultSet execute(String query)
Executes the provided query.This is a convenience method for
execute(new SimpleStatement(query)).- Parameters:
query- the CQL query to execute.- Returns:
- the result of the query. That result will never be null but can be empty (and will be for any non SELECT query).
- Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to execute this query.QueryExecutionException- if the query triggered an execution exception, i.e. an exception thrown by Cassandra when it cannot execute the query with the requested consistency level successfully.QueryValidationException- if the query if invalid (syntax error, unauthorized or any other validation problem).
-
execute
ResultSet execute(String query, Object... values)
Executes the provided query using the provided values.This is a convenience method for
execute(new SimpleStatement(query, values)).- Parameters:
query- the CQL query to execute.values- values required for the execution ofquery. SeeSimpleStatement(String, Object...)for more details.- Returns:
- the result of the query. That result will never be null but can be empty (and will be for any non SELECT query).
- Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to execute this query.QueryExecutionException- if the query triggered an execution exception, i.e. an exception thrown by Cassandra when it cannot execute the query with the requested consistency level successfully.QueryValidationException- if the query if invalid (syntax error, unauthorized or any other validation problem).UnsupportedFeatureException- if version 1 of the protocol is in use (i.e. if you've forced version 1 throughCluster.Builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion)or you use Cassandra 1.2).
-
execute
ResultSet execute(String query, Map<String,Object> values)
Executes the provided query using the provided named values.This is a convenience method for
execute(new SimpleStatement(query, values)).- Parameters:
query- the CQL query to execute.values- values required for the execution ofquery. SeeSimpleStatement(String, Map)for more details.- Returns:
- the result of the query. That result will never be null but can be empty (and will be for any non SELECT query).
- Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to execute this query.QueryExecutionException- if the query triggered an execution exception, i.e. an exception thrown by Cassandra when it cannot execute the query with the requested consistency level successfully.QueryValidationException- if the query if invalid (syntax error, unauthorized or any other validation problem).UnsupportedFeatureException- if version 1 or 2 of the protocol is in use (i.e. if you've forced it throughCluster.Builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion)or you use Cassandra 1.2 or 2.0).
-
execute
ResultSet execute(Statement statement)
Executes the provided query.This method blocks until at least some result has been received from the database. However, for SELECT queries, it does not guarantee that the result has been received in full. But it does guarantee that some response has been received from the database, and in particular guarantees that if the request is invalid, an exception will be thrown by this method.
- Parameters:
statement- the CQL query to execute (that can be anyStatement).- Returns:
- the result of the query. That result will never be null but can be empty (and will be for any non SELECT query).
- Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to execute this query.QueryExecutionException- if the query triggered an execution exception, i.e. an exception thrown by Cassandra when it cannot execute the query with the requested consistency level successfully.QueryValidationException- if the query if invalid (syntax error, unauthorized or any other validation problem).UnsupportedFeatureException- if the protocol version 1 is in use and a feature not supported has been used. Features that are not supported by the version protocol 1 include: BatchStatement, ResultSet paging and binary values in RegularStatement.
-
executeAsync
ResultSetFuture executeAsync(String query)
Executes the provided query asynchronously.This is a convenience method for
executeAsync(new SimpleStatement(query)).- Parameters:
query- the CQL query to execute.- Returns:
- a future on the result of the query.
-
executeAsync
ResultSetFuture executeAsync(String query, Object... values)
Executes the provided query asynchronously using the provided values.This is a convenience method for
executeAsync(new SimpleStatement(query, values)).- Parameters:
query- the CQL query to execute.values- values required for the execution ofquery. SeeSimpleStatement(String, Object...)for more details.- Returns:
- a future on the result of the query.
- Throws:
UnsupportedFeatureException- if version 1 of the protocol is in use (i.e. if you've forced version 1 throughCluster.Builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion)or you use Cassandra 1.2).
-
executeAsync
ResultSetFuture executeAsync(String query, Map<String,Object> values)
Executes the provided query asynchronously using the provided values.This is a convenience method for
executeAsync(new SimpleStatement(query, values)).- Parameters:
query- the CQL query to execute.values- values required for the execution ofquery. SeeSimpleStatement(String, Map)for more details.- Returns:
- a future on the result of the query.
- Throws:
UnsupportedFeatureException- if version 1 or 2 of the protocol is in use (i.e. if you've forced it throughCluster.Builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion)or you use Cassandra 1.2 or 2.0).
-
executeAsync
ResultSetFuture executeAsync(Statement statement)
Executes the provided query asynchronously.This method does not block. It returns as soon as the query has been passed to the underlying network stack. In particular, returning from this method does not guarantee that the query is valid or has even been submitted to a live node. Any exception pertaining to the failure of the query will be thrown when accessing the
ResultSetFuture.Note that for queries that don't return a result (INSERT, UPDATE and DELETE), you will need to access the ResultSetFuture (that is, call one of its
getmethods to make sure the query was successful.- Parameters:
statement- the CQL query to execute (that can be anyStatement).- Returns:
- a future on the result of the query.
- Throws:
UnsupportedFeatureException- if the protocol version 1 is in use and a feature not supported has been used. Features that are not supported by the version protocol 1 include: BatchStatement, ResultSet paging and binary values in RegularStatement.
-
prepare
PreparedStatement prepare(String query)
Prepares the provided query string.- Parameters:
query- the CQL query string to prepare- Returns:
- the prepared statement corresponding to
query. - Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to prepare this query.
-
prepare
PreparedStatement prepare(RegularStatement statement)
Prepares the provided query.This method behaves like
prepare(String), but the resultingPreparedStatementwill inherit some of the properties set onstatement: routing key, consistency level, serial consistency level, tracing flag, retry policy, outgoing payload, and idempotence. Concretely, this means that in the following code:RegularStatement toPrepare = new SimpleStatement("SELECT * FROM test WHERE k=?").setConsistencyLevel(ConsistencyLevel.QUORUM); PreparedStatement prepared = session.prepare(toPrepare); session.execute(prepared.bind("someValue"));the final execution will be performed with Quorum consistency.Please note that if the same CQL statement is prepared more than once, all calls to this method will return the same
PreparedStatementobject but the method will still apply the properties of the preparedStatementto this object.- Parameters:
statement- the statement to prepare- Returns:
- the prepared statement corresponding to
statement. - Throws:
NoHostAvailableException- if no host in the cluster can be contacted successfully to prepare this statement.IllegalArgumentException- ifstatement.getValues() != null(values for executing a prepared statement should be provided after preparation though thePreparedStatement.bind(java.lang.Object...)method or through a correspondingBoundStatement).
-
prepareAsync
ListenableFuture<PreparedStatement> prepareAsync(String query)
Prepares the provided query string asynchronously.This method is equivalent to
prepare(String)except that it does not block but return a future instead. Any error during preparation will be thrown when accessing the future, not by this method itself.- Parameters:
query- the CQL query string to prepare- Returns:
- a future on the prepared statement corresponding to
query.
-
prepareAsync
ListenableFuture<PreparedStatement> prepareAsync(RegularStatement statement)
Prepares the provided query asynchronously. This method behaves likeprepareAsync(String), but note that the resultingPreparedStatementwill inherit the query properties set onstatement. Concretely, this means that in the following code:RegularStatement toPrepare = new SimpleStatement("SELECT * FROM test WHERE k=?").setConsistencyLevel(ConsistencyLevel.QUORUM); PreparedStatement prepared = session.prepare(toPrepare); session.execute(prepared.bind("someValue"));the final execution will be performed with Quorum consistency.Please note that if the same CQL statement is prepared more than once, all calls to this method will return the same
PreparedStatementobject but the method will still apply the properties of the preparedStatementto this object.- Parameters:
statement- the statement to prepare- Returns:
- a future on the prepared statement corresponding to
statement. - Throws:
IllegalArgumentException- ifstatement.getValues() != null(values for executing a prepared statement should be provided after preparation though thePreparedStatement.bind(java.lang.Object...)method or through a correspondingBoundStatement).- See Also:
prepare(RegularStatement)
-
closeAsync
CloseFuture closeAsync()
Initiates a shutdown of this session instance.This method is asynchronous and return a future on the completion of the shutdown process. As soon as the session is shutdown, no new request will be accepted, but already submitted queries are allowed to complete. This method closes all connections of this session and reclaims all resources used by it.
If for some reason you wish to expedite this process, the
CloseFuture.force()can be called on the result future.This method has no particular effect if the session was already closed (in which case the returned future will return immediately).
Note that this method does not close the corresponding
Clusterinstance (which holds additional resources, in particular internal executors that must be shut down in order for the client program to terminate). If you want to do so, useCluster.close(), but note that it will close all sessions created from that cluster.- Returns:
- a future on the completion of the shutdown process.
-
close
void close()
Initiates a shutdown of this session instance and blocks until that shutdown completes.This method is a shortcut for
closeAsync().get().Note that this method does not close the corresponding
Clusterinstance (which holds additional resources, in particular internal executors that must be shut down in order for the client program to terminate). If you want to do so, useCluster.close(), but note that it will close all sessions created from that cluster.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
isClosed
boolean isClosed()
Whether this Session instance has been closed.Note that this method returns true as soon as the closing of this Session has started but it does not guarantee that the closing is done. If you want to guarantee that the closing is done, you can call
close()and wait until it returns (or call the get method oncloseAsync()with a very short timeout and check this doesn't timeout).- Returns:
trueif this Session instance has been closed,falseotherwise.
-
getCluster
Cluster getCluster()
Returns theClusterobject this session is part of.- Returns:
- the
Clusterobject this session is part of.
-
getState
Session.State getState()
Return a snapshot of the state of this Session.The returned object provides information on which hosts the session is connected to, how many connections are opened to each host, etc... The returned object is immutable, it is a snapshot of the Session State taken when this method is called.
- Returns:
- a snapshot of the state of this Session.
-
-