Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset0d06ef6c86a5fdcaf41672c6845552f05df7b69ee00b8b04aecaacf698f7f80e
Authorolim7t <omichallat+github@gmail.com> · 2015-06-30 18:00 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-06-30 18:00 +02:00
Parents4978bf2a395d, 09fb9cb33178

Browse the files at this changeset

16 files changed

modified changelog/README.md +2 −0
@@ -37,6 +37,7 @@
3737 - [improvement] Optimize internal copies of Request objects (JAVA-726)
3838 - [bug] Preserve tracing across retries (JAVA-815)
3939 - [improvement] New RetryDecision.tryNextHost() (JAVA-709)
40+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
4041
4142
4243 ### 2.1.6
@@ -272,6 +273,7 @@
272273 - [improvement] Optimize internal copies of Request objects (JAVA-726)
273274 - [bug] Preserve tracing across retries (JAVA-815)
274275 - [improvement] New RetryDecision.tryNextHost() (JAVA-709)
276+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
275277
276278 Merged from 2.0.10_fixes branch:
277279
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +2 −0
@@ -579,6 +579,8 @@
579579 logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
580580 if (metricsEnabled())
581581 metrics().getErrorMetrics().getRetries().inc();
582+ if (!retry.isRetryCurrent())
583+ logError(connection.address, exceptionToReport);
582584 retry(retry.isRetryCurrent(), retry.getRetryConsistencyLevel());
583585 break;
584586 case RETHROW:
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +4 −3
@@ -427,9 +427,10 @@
427427 * <p>
428428 * By default, this method returns {@code null} for all statements, except for
429429 * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
430- * counters or prepends/appends to a list, the result will be {@code false}, otherwise it
431- * will be {@code true}. In all cases, calling {@link #setIdempotent(boolean)} forces a
432- * value that overrides every other mechanism.
430+ * counters, prepends/appends to a list, or uses a function call or
431+ * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value,
432+ * the result will be {@code false}; otherwise it will be {@code true}.
433+ * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism.
433434 *
434435 * @return whether this statement is idempotent, or {@code null} to use
435436 * {@link QueryOptions#getDefaultIdempotence()}.
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +1 −1
@@ -63,7 +63,7 @@
6363
6464 @Override
6565 boolean isIdempotent() {
66- return true;
66+ return Utils.isIdempotent(value);
6767 }
6868 }
6969
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +7 −2
@@ -79,6 +79,8 @@
7979 names.add(name);
8080 values.add(value);
8181 checkForBindMarkers(value);
82+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(value))
83+ this.setNonIdempotentOps();
8284 maybeAddRoutingKey(name, value);
8385 return this;
8486 }
@@ -113,8 +115,11 @@
113115 this.names.addAll(names);
114116 this.values.addAll(values);
115117 for (int i = 0; i < names.size(); i++) {
116- checkForBindMarkers(values.get(i));
117- maybeAddRoutingKey(names.get(i), values.get(i));
118+ Object value = values.get(i);
119+ checkForBindMarkers(value);
120+ maybeAddRoutingKey(names.get(i), value);
121+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(value))
122+ this.setNonIdempotentOps();
118123 }
119124 return this;
120125 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +18 −0
@@ -959,6 +959,24 @@
959959 return new Utils.FCall(name, parameters);
960960 }
961961
962+ /**
963+ * Creates a {@code now()} function call.
964+ *
965+ * @return the function call.
966+ */
967+ public static Object now() {
968+ return new Utils.FCall("now");
969+ }
970+
971+ /**
972+ * Creates a {@code uuid()} function call.
973+ *
974+ * @return the function call.
975+ */
976+ public static Object uuid() {
977+ return new Utils.FCall("uuid");
978+ }
979+
962980 /**
963981 * Declares that the name in argument should be treated as a column name.
964982 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +1 −1
@@ -175,7 +175,7 @@
175175 */
176176 public Assignments and(Assignment assignment) {
177177 statement.setCounterOp(assignment instanceof CounterAssignment);
178- if (!assignment.isIdempotent())
178+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(assignment))
179179 statement.setNonIdempotentOps();
180180 assignments.add(assignment);
181181 checkForBindMarkers(assignment);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +30 −0
@@ -22,6 +22,8 @@
2222 import java.util.*;
2323 import java.util.regex.Pattern;
2424
25+import static com.google.common.base.Preconditions.checkNotNull;
26+
2527 import com.datastax.driver.core.DataType;
2628 import com.datastax.driver.core.ProtocolVersion;
2729 import com.datastax.driver.core.TupleValue;
@@ -264,6 +266,31 @@
264266 return false;
265267 }
266268
269+ static boolean isIdempotent(Object value) {
270+ if(value == null) {
271+ return true;
272+ } else if (value instanceof Assignment) {
273+ Assignment assignment = (Assignment)value;
274+ return assignment.isIdempotent();
275+ } else if (value instanceof FCall) {
276+ return false;
277+ } else if (value instanceof RawString) {
278+ return false;
279+ } else if(value instanceof Collection) {
280+ for (Object elt : ((Collection)value)) {
281+ if(!isIdempotent(elt))
282+ return false;
283+ }
284+ return true;
285+ } else if (value instanceof Map) {
286+ for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
287+ if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue()))
288+ return false;
289+ }
290+ }
291+ return true;
292+ }
293+
267294 private static StringBuilder appendValueString(String value, StringBuilder sb) {
268295 return sb.append(DataType.text().format(value));
269296 }
@@ -334,10 +361,12 @@
334361 }
335362
336363 static class FCall {
364+
337365 private final String name;
338366 private final Object[] parameters;
339367
340368 FCall(String name, Object... parameters) {
369+ checkNotNull(name);
341370 this.name = name;
342371 this.parameters = parameters;
343372 }
@@ -354,6 +383,7 @@
354383 sb.append(')');
355384 return sb.toString();
356385 }
386+
357387 }
358388
359389 static class CName {
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +6 −2
@@ -214,11 +214,15 @@
214214 .build()
215215 );
216216 // when
217+ // when
217218 try {
218219 session.execute(query);
219- fail("Should have thrown UnavailableException");
220- } catch (UnavailableException e) {
220+ fail("Should have thrown NoHostAvailableException");
221+ } catch(NoHostAvailableException e) {
221222 // ok
223+ Throwable error = e.getErrors().get(hostAddress);
224+ assertThat(error).isNotNull();
225+ assertThat(error).isInstanceOf(UnavailableException.class);
222226 }
223227 // then
224228 String line = errorAppender.waitAndGet(5000);
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +95 −99
@@ -17,11 +17,12 @@
1717
1818 import com.datastax.driver.core.utils.SocketChannelMonitor;
1919 import com.google.common.collect.Lists;
20-import com.google.common.util.concurrent.*;
20+import com.google.common.util.concurrent.ListenableFuture;
21+import com.google.common.util.concurrent.ListeningExecutorService;
22+import com.google.common.util.concurrent.MoreExecutors;
23+import com.google.common.util.concurrent.Uninterruptibles;
2124 import org.slf4j.Logger;
2225 import org.slf4j.LoggerFactory;
23-import org.testng.annotations.AfterMethod;
24-import org.testng.annotations.BeforeMethod;
2526 import org.testng.annotations.Test;
2627
2728 import java.net.InetSocketAddress;
@@ -41,8 +42,6 @@
4142
4243 private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
4344
44- private List<InetSocketAddress> contactPoints;
45-
4645 public SessionStressTest() {
4746 // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
4847 executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
@@ -53,28 +52,6 @@
5352 return new ArrayList<String>(0);
5453 }
5554
56- @BeforeMethod
57- public void setUp() {
58- contactPoints = Collections.singletonList(hostAddress);
59- // override inherited field with a new cluster object and ensure 0 sessions and connections
60- channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
61- stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
62- .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
63- .withNettyOptions(channelMonitor.nettyOptions()).build();
64- stressCluster.init();
65- }
66-
67- @AfterMethod
68- public void tearDown() {
69- stressCluster.close();
70-
71- // Ensure no channels remain open.
72- assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
73-
74- channelMonitor.stop();
75- channelMonitor.report();
76- }
77-
7855 /**
7956 * Stress test on opening/closing sessions.
8057 * <p/>
@@ -100,82 +77,101 @@
10077 */
10178 @Test(groups = "long")
10279 public void sessions_should_not_leak_connections() {
103- // The cluster has been initialized, we should have 1 connection.
104- assertEquals(stressCluster.manager.sessions.size(), 0);
105- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
106-
107- // The first session initializes the cluster and its control connection
108- // This is a local cluster so we also have 2 connections per session
109- Session session = stressCluster.connect();
110- assertEquals(stressCluster.manager.sessions.size(), 1);
111- int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster);
112- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
113- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
114-
115- // Closing the session keeps the control connection opened
116- session.close();
117- assertEquals(stressCluster.manager.sessions.size(), 0);
118- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
119- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
120-
121- int nbOfSessions = 2000;
122- int halfOfTheSessions = nbOfSessions / 2;
123- int nbOfIterations = 5;
124- int sleepTime = 20;
125-
126- for (int iteration = 1; iteration <= nbOfIterations; iteration++) {
127- logger.info("On iteration {}/{}.", iteration, nbOfIterations);
128- logger.info("Creating {} sessions.", nbOfSessions);
129- waitFor(openSessionsConcurrently(nbOfSessions));
130-
131- // We should see the exact number of opened sessions
132- // Since we have 2 connections per session, we should see 2 * sessions + control connection
133- assertEquals(stressCluster.manager.sessions.size(), nbOfSessions);
134- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
135- coreConnections * nbOfSessions + 1);
136- assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
137-
138- // Close half of the sessions asynchronously
139- logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
140- waitFor(closeSessionsConcurrently(halfOfTheSessions));
141-
142- // Check that we have the right number of sessions and connections
143- assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
144- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
145- coreConnections * (nbOfSessions / 2) + 1);
146- assertEquals(channelMonitor.openChannels(contactPoints).size(),
147- coreConnections * (nbOfSessions / 2) + 1);
148-
149- // Close and open the same number of sessions concurrently
150- logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions);
151- CountDownLatch startSignal = new CountDownLatch(2);
152- List<ListenableFuture<Session>> openSessionFutures =
153- openSessionsConcurrently(halfOfTheSessions, startSignal);
154- List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
155- startSignal);
156- startSignal.countDown();
157- waitFor(openSessionFutures);
158- waitFor(closeSessionsFutures);
159-
160- // Check that we have the same number of sessions and connections
161- assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
162- assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
163- coreConnections * (nbOfSessions / 2) + 1);
164- assertEquals(channelMonitor.openChannels(contactPoints).size(),
165- coreConnections * (nbOfSessions / 2) + 1);
166-
167- // Close the remaining sessions
168- logger.info("Closing remaining {} sessions.", halfOfTheSessions);
169- waitFor(closeSessionsConcurrently(halfOfTheSessions));
170-
171- // Check that we have a clean state
80+ List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
81+ // override inherited field with a new cluster object and ensure 0 sessions and connections
82+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
83+ stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
84+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
85+ .withNettyOptions(channelMonitor.nettyOptions()).build();
86+
87+ try {
88+ stressCluster.init();
89+
90+ // The cluster has been initialized, we should have 1 connection.
91+ assertEquals(stressCluster.manager.sessions.size(), 0);
92+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
93+
94+ // The first session initializes the cluster and its control connection
95+ // This is a local cluster so we also have 2 connections per session
96+ Session session = stressCluster.connect();
97+ assertEquals(stressCluster.manager.sessions.size(), 1);
98+ int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster);
99+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
100+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
101+
102+ // Closing the session keeps the control connection opened
103+ session.close();
172104 assertEquals(stressCluster.manager.sessions.size(), 0);
173105 assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
174106 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
175107
176- // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
177- logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
178- Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS);
108+ int nbOfSessions = 2000;
109+ int halfOfTheSessions = nbOfSessions / 2;
110+ int nbOfIterations = 5;
111+ int sleepTime = 20;
112+
113+ for (int iteration = 1; iteration <= nbOfIterations; iteration++) {
114+ logger.info("On iteration {}/{}.", iteration, nbOfIterations);
115+ logger.info("Creating {} sessions.", nbOfSessions);
116+ waitFor(openSessionsConcurrently(nbOfSessions));
117+
118+ // We should see the exact number of opened sessions
119+ // Since we have 2 connections per session, we should see 2 * sessions + control connection
120+ assertEquals(stressCluster.manager.sessions.size(), nbOfSessions);
121+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
122+ coreConnections * nbOfSessions + 1);
123+ assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
124+
125+ // Close half of the sessions asynchronously
126+ logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
127+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
128+
129+ // Check that we have the right number of sessions and connections
130+ assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
131+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
132+ coreConnections * (nbOfSessions / 2) + 1);
133+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
134+ coreConnections * (nbOfSessions / 2) + 1);
135+
136+ // Close and open the same number of sessions concurrently
137+ logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions);
138+ CountDownLatch startSignal = new CountDownLatch(2);
139+ List<ListenableFuture<Session>> openSessionFutures =
140+ openSessionsConcurrently(halfOfTheSessions, startSignal);
141+ List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
142+ startSignal);
143+ startSignal.countDown();
144+ waitFor(openSessionFutures);
145+ waitFor(closeSessionsFutures);
146+
147+ // Check that we have the same number of sessions and connections
148+ assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
149+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
150+ coreConnections * (nbOfSessions / 2) + 1);
151+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
152+ coreConnections * (nbOfSessions / 2) + 1);
153+
154+ // Close the remaining sessions
155+ logger.info("Closing remaining {} sessions.", halfOfTheSessions);
156+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
157+
158+ // Check that we have a clean state
159+ assertEquals(stressCluster.manager.sessions.size(), 0);
160+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
161+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
162+
163+ // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
164+ logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
165+ Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS);
166+ }
167+ } finally {
168+ stressCluster.close();
169+
170+ // Ensure no channels remain open.
171+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
172+
173+ channelMonitor.stop();
174+ channelMonitor.report();
179175 }
180176 }
181177
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +56 −3
@@ -16,6 +16,9 @@
1616 package com.datastax.driver.core;
1717
1818 import com.google.common.collect.ImmutableList;
19+import com.google.common.collect.ImmutableMap;
20+import com.google.common.collect.Lists;
21+import com.google.common.collect.Sets;
1922 import org.testng.annotations.Test;
2023
2124 import static org.assertj.core.api.Assertions.assertThat;
@@ -89,15 +92,65 @@
8992 return ImmutableList.<BuiltStatement>of(
9093 update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
9194 update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
92- update("foo").with(put("m", "a", 1)).where(eq("k", 1)) // put in map
95+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
96+
97+ // select statements should be idempotent even with function calls
98+ select().countAll() .from("foo").where(eq("k", 1)),
99+ select().ttl("v") .from("foo").where(eq("k", 1)),
100+ select().writeTime("v") .from("foo").where(eq("k", 1)),
101+ select().fcall("token", "k").from("foo").where(eq("k", 1))
102+
93103 );
94104 }
95105
96106 private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
97- return ImmutableList.<BuiltStatement>of(
107+ return ImmutableList.of(
98108 update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
99109 update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
100- update("foo").with(incr("c")).where(eq("k", 1)) // counter update
110+ update("foo").with(incr("c")).where(eq("k", 1)), // counter update
111+
112+ // function calls
113+
114+ insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
115+ insertInto("foo").value("k", 1).value("v", now()),
116+ insertInto("foo").value("k", 1).value("v", uuid()),
117+
118+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
119+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
120+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
121+
122+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
123+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
124+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
125+
126+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
127+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
128+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
129+
130+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
131+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
132+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
133+
134+ update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
135+ update("foo").with(set("v", now())) .where(eq("k", 1)),
136+ update("foo").with(set("v", uuid())) .where(eq("k", 1)),
137+
138+ update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
139+ update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
140+ update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
141+
142+ // raw() calls
143+
144+ insertInto("foo").value("k", 1).value("v", raw("foo()")),
145+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
146+
147+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
148+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
149+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
150+
151+ update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
152+ update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
153+
101154 );
102155 }
103156 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +19 −0
@@ -22,6 +22,8 @@
2222 import com.google.common.collect.ImmutableMap;
2323 import org.mockito.Mockito;
2424 import org.scassandra.http.client.PrimingRequest;
25+import org.testng.annotations.AfterClass;
26+import org.testng.annotations.AfterMethod;
2527 import org.testng.annotations.BeforeClass;
2628 import org.testng.annotations.BeforeMethod;
2729
@@ -103,6 +105,10 @@
103105 }
104106
105107 protected ResultSet query() {
108+ return query(session);
109+ }
110+
111+ protected ResultSet query(Session session) {
106112 return session.execute("mock query");
107113 }
108114
@@ -125,4 +131,17 @@
125131 protected void assertQueried(int hostNumber, int times) {
126132 assertThat(scassandras.retrieveQueries(hostNumber)).hasSize(times);
127133 }
134+
135+ @AfterMethod(groups = "short")
136+ public void afterMethod() {
137+ scassandras.clearAllPrimes();
138+ if (cluster != null)
139+ cluster.close();
140+ }
141+
142+ @AfterClass(groups = "short")
143+ public void afterClass() {
144+ if (scassandras != null)
145+ scassandras.stop();
146+ }
128147 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +48 −0
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.Cluster;
20+import com.datastax.driver.core.Metrics;
21+import com.datastax.driver.core.Session;
22+import com.datastax.driver.core.exceptions.NoHostAvailableException;
1823 import org.testng.annotations.Test;
1924
2025 import static org.assertj.core.api.Assertions.assertThat;
@@ -27,6 +32,8 @@
2732 import com.datastax.driver.core.exceptions.UnavailableException;
2833 import com.datastax.driver.core.exceptions.WriteTimeoutException;
2934
35+import java.util.Collections;
36+
3037 public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3138 public DefaultRetryPolicyIntegrationTest() {
3239 super(DefaultRetryPolicy.INSTANCE);
@@ -94,4 +101,45 @@
94101 assertQueried(2, 1);
95102 assertQueried(3, 0);
96103 }
104+
105+ @Test(groups = "short")
106+ public void should_rethrow_unavailable_in_no_host_available_exception() {
107+ LoadBalancingPolicy firstHostOnlyPolicy =
108+ new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
109+ Collections.singletonList(host1.getSocketAddress()));
110+
111+ Cluster whiteListedCluster = Cluster.builder()
112+ .addContactPoint(CCMBridge.ipOfNode(1))
113+ .withRetryPolicy(retryPolicy)
114+ .withLoadBalancingPolicy(firstHostOnlyPolicy)
115+ .build();
116+
117+ try {
118+ Session whiteListedSession = whiteListedCluster.connect();
119+ // Clear all activity as result of connect.
120+ scassandras.clearAllRecordedActivity();
121+
122+ simulateError(1, unavailable);
123+
124+ try {
125+ query(whiteListedSession);
126+ fail("expected an NoHostAvailableException");
127+ } catch(NoHostAvailableException e) {
128+ // ok
129+ Throwable error = e.getErrors().get(host1.getSocketAddress());
130+ assertThat(error).isNotNull();
131+ assertThat(error).isInstanceOf(UnavailableException.class);
132+ }
133+
134+ assertOnUnavailableWasCalled(1);
135+ // We expect a retry, but it was never sent because there were no more hosts.
136+ Metrics.Errors whiteListErrors = whiteListedCluster.getMetrics().getErrorMetrics();
137+ assertThat(whiteListErrors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
138+ assertQueried(1, 1);
139+ assertQueried(2, 0);
140+ assertQueried(3, 0);
141+ } finally {
142+ whiteListedCluster.close();
143+ }
144+ }
97145 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +6 −2
@@ -19,6 +19,7 @@
1919
2020 import static java.util.concurrent.TimeUnit.SECONDS;
2121
22+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2223 import org.testng.annotations.Test;
2324
2425 import static org.assertj.core.api.Assertions.assertThat;
@@ -111,9 +112,12 @@
111112 // when
112113 try {
113114 session.execute(query);
114- fail("Should have thrown UnavailableException");
115- } catch(UnavailableException e) {
115+ fail("Should have thrown NoHostAvailableException");
116+ } catch(NoHostAvailableException e) {
116117 // ok
118+ Throwable error = e.getErrors().get(hostAddress);
119+ assertThat(error).isNotNull();
120+ assertThat(error).isInstanceOf(UnavailableException.class);
117121 }
118122 // then
119123 // wait until trackers have been notified
modified features/speculative_execution/README.md +8 −6
@@ -78,12 +78,14 @@
7878 about what the query actually does. Therefore:
7979
8080 * **`Statement#isIdempotent()` is only computed automatically for
81- statements built with [QueryBuilder][QueryBuilder]**. Note that there
82- is a known issue in 2.1.6 where calls to `now()` or `uuid()` are not
83- taken into account (see
84- [JAVA-733](https://datastax-oss.atlassian.net/browse/JAVA-733)). If
85- you're using these CQL functions with built statements, force
86- idempotence to `false` manually (see below);
81+ statements built with [QueryBuilder][QueryBuilder]**.
82+ Note that the driver takes a rather conservative approach with uses
83+ of `fcall()` or `raw()`: whenever they appear in a value to be
84+ inserted in the database (like the values of an `Insert` or the
85+ right-hand side of an assignment in an `Update`), the statement
86+ will be considered non-idempotent by default. If you know that your
87+ CQL functions or expressions are safe, force idempotence to `true`
88+ on the statement manually (see below);
8789 * **for all other types of statements, it defaults to `false`.** You'll
8890 need to set it manually, with one of the mechanism described below.
8991
modified upgrade_guide/README.md +4 −0
@@ -142,6 +142,10 @@
142142 because of a network partition) but can still answer to the client normally.
143143 In this case, trying another node has a chance of success.
144144 The previous behaviour was to always throw an exception.
145+2. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
146+ or `raw()` is used to build a value to be inserted in the database.
147+ If you know that the CQL functions or expressions are safe, use
148+ `setIdempotent(true)` on the statement.
145149
146150 ### 2.0.x to 2.0.10
147151