Elffuss BraidHub

kikocis/java-driver public

Add Session.prepareAsync

JAVA-224 #fixes
Changesetc628d3c56e181dfd6e4a8230e87189c8955bba7b88e26d11c8b2f3fb90052c18
AuthorPeter Fodor <fodpeter@gmail.com> · 2013-12-18 19:19 +01:00
CommitterSylvain Lebresne <sylvain@datastax.com> · 2014-02-18 16:07 +01:00
Parentsffed01c5e379

Browse the files at this changeset

4 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -6,6 +6,7 @@
66
77 - [improvement] Make most main objects interface to facilitate testing/mocking (JAVA-195)
88 - [improvement] Avoid preparing a statement multiple time per host with multiple sessions
9+- [improvement] Adds Session#prepareAsync calls (JAVA-224)
910 - [bug] Fix potential thread leaks when shutting down Metrics (JAVA-232)
1011 - [bug] Fix potential NPE in HostConnectionPool (JAVA-231)
1112 - [bug] Make sure connections are returned to the right pools (JAVA-255)
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +3 −5
@@ -144,8 +144,7 @@
144144 try {
145145 return Uninterruptibles.getUninterruptibly(this);
146146 } catch (ExecutionException e) {
147- extractCauseFromExecutionException(e);
148- throw new AssertionError();
147+ throw extractCauseFromExecutionException(e);
149148 }
150149 }
151150
@@ -153,8 +152,7 @@
153152 try {
154153 return Uninterruptibles.getUninterruptibly(this, timeout, unit);
155154 } catch (ExecutionException e) {
156- extractCauseFromExecutionException(e);
157- throw new AssertionError();
155+ throw extractCauseFromExecutionException(e);
158156 }
159157 }
160158
@@ -167,7 +165,7 @@
167165 return true;
168166 }
169167
170- static void extractCauseFromExecutionException(ExecutionException e) {
168+ static RuntimeException extractCauseFromExecutionException(ExecutionException e) {
171169 // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
172170 // created on the I/O thread receiving the response. Which means that the stacktrace associated
173171 // with said cause will make no mention of the current thread. This is painful for say, finding
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +29 −2
@@ -20,6 +20,7 @@
2020 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2121 import com.datastax.driver.core.exceptions.QueryExecutionException;
2222 import com.datastax.driver.core.exceptions.QueryValidationException;
23+import com.google.common.util.concurrent.ListenableFuture;
2324
2425 /**
2526 * A session holds connections to a Cassandra cluster, allowing it to be queried.
@@ -85,7 +86,7 @@
8586
8687 /**
8788 * Executes the provided query asynchronously.
88- *
89+ * <p>
8990 * This is a convenience method for {@code executeAsync(new SimpleStatement(query))}.
9091 *
9192 * @param query the CQL query to execute.
@@ -101,7 +102,7 @@
101102 * this method does not guarantee that the query is valid or has even been
102103 * submitted to a live node. Any exception pertaining to the failure of the
103104 * query will be thrown when accessing the {@link ResultSetFuture}.
104- *
105+ * <p>
105106 * Note that for queries that doesn't return a result (INSERT, UPDATE and
106107 * DELETE), you will need to access the ResultSetFuture (that is call one of
107108 * its get method to make sure the query was successful.
@@ -149,6 +150,32 @@
149150 */
150151 public PreparedStatement prepare(Statement statement);
151152
153+ /**
154+ * Prepares the provided query string asynchronously.
155+ * <p>
156+ * This method is equilavent to {@link #prepare(String)} except that it
157+ * does not block but return a future instead. Any error during preparation will
158+ * be thrown when accessing the future, not by this method itself.
159+ *
160+ * @param query the CQL query string to prepare
161+ * @return a future on the prepared statement corresponding to {@code query}.
162+ */
163+ public ListenableFuture<PreparedStatement> prepareAsync(String query);
164+
165+ /**
166+ * Prepares the provided query asynchronously.
167+ * <p>
168+ * This method is essentially a shortcut for {@code prepareAsync(statement.getQueryString())},
169+ * but with the additional effect that the resulting {@code
170+ * PreparedStamenent} will inherit the query properties set on {@code statement}.
171+ *
172+ * @param statement the statement to prepare
173+ * @return a future on the prepared statement corresponding to {@code statement}.
174+ *
175+ * @see Session#prepare(Statement)
176+ */
177+ public ListenableFuture<PreparedStatement> prepareAsync(Statement statement);
178+
152179 /**
153180 * Shuts down this session instance.
154181 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +65 −47
@@ -23,6 +23,7 @@
2323 import java.util.concurrent.*;
2424 import java.util.concurrent.atomic.AtomicBoolean;
2525
26+import com.google.common.base.Function;
2627 import com.google.common.util.concurrent.*;
2728 import org.apache.cassandra.transport.Message;
2829 import org.apache.cassandra.transport.messages.*;
@@ -91,23 +92,43 @@
9192 }
9293
9394 public PreparedStatement prepare(String query) {
95+ try {
96+ return Uninterruptibles.getUninterruptibly(prepareAsync(query));
97+ } catch (ExecutionException e) {
98+ throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
99+ }
100+ }
101+
102+ public PreparedStatement prepare(Statement statement) {
103+ try {
104+ return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
105+ } catch (ExecutionException e) {
106+ throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
107+ }
108+ }
109+
110+ public ListenableFuture<PreparedStatement> prepareAsync(String query) {
94111 Connection.Future future = new Connection.Future(new PrepareMessage(query));
95112 execute(future, Query.DEFAULT);
96113 return toPreparedStatement(query, future);
97114 }
98115
99- public PreparedStatement prepare(Statement statement) {
100- PreparedStatement prepared = prepare(statement.getQueryString());
101-
102- ByteBuffer routingKey = statement.getRoutingKey();
103- if (routingKey != null)
104- prepared.setRoutingKey(routingKey);
105- prepared.setConsistencyLevel(statement.getConsistencyLevel());
106- if (statement.isTracing())
107- prepared.enableTracing();
108- prepared.setRetryPolicy(statement.getRetryPolicy());
109-
110- return prepared;
116+ public ListenableFuture<PreparedStatement> prepareAsync(final Statement statement) {
117+ ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString());
118+ return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
119+ @Override
120+ public PreparedStatement apply(PreparedStatement prepared) {
121+ ByteBuffer routingKey = statement.getRoutingKey();
122+ if (routingKey != null)
123+ prepared.setRoutingKey(routingKey);
124+ prepared.setConsistencyLevel(statement.getConsistencyLevel());
125+ if (statement.isTracing())
126+ prepared.enableTracing();
127+ prepared.setRetryPolicy(statement.getRetryPolicy());
128+
129+ return prepared;
130+ }
131+ });
111132 }
112133
113134 public void shutdown() {
@@ -134,42 +155,39 @@
134155 return cluster;
135156 }
136157
137- private PreparedStatement toPreparedStatement(String query, Connection.Future future) {
138- try {
139- Message.Response response = Uninterruptibles.getUninterruptibly(future);
140- switch (response.type) {
141- case RESULT:
142- ResultMessage rm = (ResultMessage)response;
143- switch (rm.kind) {
144- case PREPARED:
145- ResultMessage.Prepared pmsg = (ResultMessage.Prepared)rm;
146- PreparedStatement stmt = PreparedStatement.fromMessage(pmsg, cluster.getMetadata(), query, poolsState.keyspace);
147- cluster.manager.addPrepared(stmt);
148- try {
149- // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
150- // If that changes, we'll have to make sure this propagate to other sessions too.
151- prepare(stmt.getQueryString(), future.getAddress());
152- } catch (InterruptedException e) {
153- Thread.currentThread().interrupt();
154- // This method doesn't propagate interruption, at least not for now. However, if we've
155- // interrupted preparing queries on other node it's not a problem as we'll re-prepare
156- // later if need be. So just ignore.
157- }
158- return stmt;
159- default:
160- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
161- }
162- case ERROR:
163- DefaultResultSetFuture.extractCause(DefaultResultSetFuture.convertException(((ErrorMessage)response).error));
164- break;
165- default:
166- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
158+ private ListenableFuture<PreparedStatement> toPreparedStatement(final String query, final Connection.Future future) {
159+ return Futures.transform(future, new Function<Message.Response, PreparedStatement>() {
160+ public PreparedStatement apply(Message.Response response) {
161+ switch (response.type) {
162+ case RESULT:
163+ ResultMessage rm = (ResultMessage)response;
164+ switch (rm.kind) {
165+ case PREPARED:
166+ ResultMessage.Prepared pmsg = (ResultMessage.Prepared)rm;
167+ PreparedStatement stmt = PreparedStatement.fromMessage(pmsg, cluster.getMetadata(), query, poolsState.keyspace);
168+ cluster.manager.addPrepared(stmt);
169+ try {
170+ // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
171+ // If that changes, we'll have to make sure this propagate to other sessions too.
172+ prepare(stmt.getQueryString(), future.getAddress());
173+ } catch (InterruptedException e) {
174+ Thread.currentThread().interrupt();
175+ // This method doesn't propagate interruption, at least not for now. However, if we've
176+ // interrupted preparing queries on other node it's not a problem as we'll re-prepare
177+ // later if need be. So just ignore.
178+ }
179+ return stmt;
180+ default:
181+ throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
182+ }
183+ case ERROR:
184+ DefaultResultSetFuture.extractCause(DefaultResultSetFuture.convertException(((ErrorMessage)response).error));
185+ throw new AssertionError();
186+ default:
187+ throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
188+ }
167189 }
168- throw new AssertionError();
169- } catch (ExecutionException e) {
170- DefaultResultSetFuture.extractCauseFromExecutionException(e);
171- throw new AssertionError();
172- }
190+ });
173191 }
174192
175193 Connection.Factory connectionFactory() {