Elffuss BraidHub

kikocis/java-driver public

9b39ff6a48bf · 14.9 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import com.datastax.driver.core.*;
19import com.datastax.driver.core.exceptions.NoHostAvailableException;
20import com.datastax.driver.core.exceptions.UnavailableException;
21import com.datastax.driver.core.utils.CassandraVersion;
22import com.datastax.driver.mapping.annotations.PartitionKey;
23import com.datastax.driver.mapping.annotations.Table;
24import org.testng.SkipException;
25import org.testng.annotations.BeforeMethod;
26import org.testng.annotations.Test;
27
28import java.util.concurrent.ExecutionException;
29
30import static com.datastax.driver.core.ConsistencyLevel.*;
31import static com.datastax.driver.core.ProtocolVersion.V1;
32import static com.datastax.driver.mapping.Mapper.Option;
33import static org.assertj.core.api.Assertions.assertThat;
34import static org.assertj.core.api.Assertions.fail;
35
36@SuppressWarnings("unused")
37public class MapperOptionTest extends CCMTestsSupport {
38
39 ProtocolVersion protocolVersion;
40 Mapper<User> mapper;
41
42 @Override
43 public void onTestContextInitialized() {
44 execute("CREATE TABLE user (key int primary key, v text)");
45 }
46
47 @BeforeMethod(groups = "short")
48 public void setup() {
49 mapper = new MappingManager(session()).mapper(User.class);
50 protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
51 }
52
53 @Test(groups = "short")
54 @CassandraVersion("2.0.0")
55 void should_use_save_options() throws Exception {
56 Long tsValue = futureTimestamp();
57 mapper.save(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
58 assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
59 Long tsReturned = session().execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
60 assertThat(tsReturned).isEqualTo(tsValue);
61 }
62
63 @Test(groups = "short")
64 @CassandraVersion("2.0.0")
65 void should_use_delete_options() {
66 User todelete = new User(45, "todelete");
67 mapper.save(todelete);
68 Option opt = Option.timestamp(35);
69 BoundStatement bs = (BoundStatement) mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
70 assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
71 assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
72 }
73
74 @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
75 @CassandraVersion("2.0.0")
76 void should_use_get_options() {
77 User user = new User(45, "toget");
78 mapper.save(user);
79
80 BoundStatement bs = (BoundStatement) mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
81 assertThat(bs.isTracing()).isTrue();
82 assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
83
84 ResultSet rs = session().execute(bs);
85 assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
86 User us = mapper.map(rs).one();
87 assertThat(us.getV()).isEqualTo("toget");
88
89 mapper.getQuery(45, Option.timestamp(1337));
90 }
91
92 @Test(groups = "short")
93 @CassandraVersion("2.0.0")
94 void should_use_options_only_once() {
95 Long tsValue = futureTimestamp();
96 mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
97 mapper.save(new User(44, "test"));
98 Long tsReturned = session().execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
99 // Assuming we cannot go back in time (yet) and execute the write at ts=1
100 assertThat(tsReturned).isNotEqualTo(tsValue);
101 }
102
103 @Test(groups = "short")
104 @CassandraVersion("2.0.0")
105 void should_use_default_options() {
106 mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
107 BoundStatement bs = (BoundStatement) mapper.saveQuery(new User(46, "rjhrgce"));
108 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
109
110 mapper.resetDefaultSaveOptions();
111 bs = (BoundStatement) mapper.saveQuery(new User(47, "rjhrgce"));
112 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
113
114 mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
115 bs = (BoundStatement) mapper.deleteQuery(47);
116 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
117 assertThat(bs.isTracing()).isTrue();
118
119 mapper.resetDefaultDeleteOptions();
120 bs = (BoundStatement) mapper.deleteQuery(47);
121 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
122 assertThat(bs.isTracing()).isFalse();
123
124 bs = (BoundStatement) mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
125 assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
126
127 mapper.setDefaultGetOptions(Option.tracing(true));
128 bs = (BoundStatement) mapper.getQuery(46);
129 assertThat(bs.isTracing()).isTrue();
130
131 mapper.resetDefaultGetOptions();
132 bs = (BoundStatement) mapper.getQuery(46);
133 assertThat(bs.isTracing()).isFalse();
134 }
135
136 @Test(groups = "short")
137 @CassandraVersion("2.0.0")
138 void should_prioritize_option_over_model_consistency() {
139 // Generate Write Query and ensure User model writeConsistency is used.
140 User user = new User(1859, "Steve");
141 Statement saveDefault = mapper.saveQuery(user);
142 assertThat(saveDefault.getConsistencyLevel()).isEqualTo(ONE);
143
144 // Generate Write Query and ensure provided Option for consistencyLevel is used.
145 Statement saveProvidedCL = mapper.saveQuery(user, Option.consistencyLevel(QUORUM));
146 assertThat(saveProvidedCL.getConsistencyLevel()).isEqualTo(QUORUM);
147
148 // Generate Read Query and ensure User model readConsistency is used.
149 Statement readDefault = mapper.getQuery(1859);
150 assertThat(readDefault.getConsistencyLevel()).isEqualTo(LOCAL_ONE);
151
152 // Generate Ready Query and ensure provided Option for consistencyLevel is used.
153 Statement readProvidedCL = mapper.getQuery(1859, Option.consistencyLevel(LOCAL_QUORUM));
154 assertThat(readProvidedCL.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
155 }
156
157 @Test(groups = "short")
158 @CassandraVersion("2.0.0")
159 void should_use_explicit_options_over_default_options() {
160 long defaultTimestamp = futureTimestamp();
161 long explicitTimestamp = futureTimestamp();
162
163 mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
164
165 mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
166 Long savedTimestamp = session().execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
167 assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
168 }
169
170 /**
171 * Cover all versions of save() to check that methods that call each other properly propagate the options
172 */
173 @Test(groups = "short")
174 @CassandraVersion("2.0.0")
175 void should_use_save_options_for_all_variants() throws ExecutionException, InterruptedException {
176 Long timestamp = futureTimestamp();
177 User user = new User(42, "helloworld");
178
179 mapper.save(user, Option.timestamp(timestamp));
180 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
181 mapper.delete(user.getKey());
182
183 mapper.saveAsync(user, Option.timestamp(timestamp)).get();
184 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
185 mapper.delete(user.getKey());
186
187 session().execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
188 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
189 mapper.delete(user.getKey());
190
191 // Set as default and try optionless methods
192 mapper.setDefaultSaveOptions(Option.timestamp(timestamp));
193
194 mapper.save(user);
195 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
196 mapper.delete(user.getKey());
197
198 mapper.saveAsync(user).get();
199 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
200 mapper.delete(user.getKey());
201
202 session().execute(mapper.saveQuery(user));
203 assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
204 mapper.delete(user.getKey());
205 }
206
207 private Long getWriteTime(int key) {
208 Row row = session().execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
209 return row.getLong(0);
210 }
211
212 @Test(groups = "short")
213 @CassandraVersion("2.0.0")
214 void should_use_get_options_for_all_variants() throws InterruptedException {
215 try {
216 mapper.get(42, Option.consistencyLevel(TWO));
217 fail("Expected a NoHostAvailableException");
218 } catch (NoHostAvailableException e) {
219 assertFirstNodeUnavailable(e);
220 }
221
222 try {
223 mapper.getAsync(42, Option.consistencyLevel(TWO)).get();
224 fail("Expected an ExecutionException");
225 } catch (ExecutionException e) {
226 assertFirstNodeUnavailable(e);
227 }
228
229 Statement statement = mapper.getQuery(42, Option.consistencyLevel(TWO));
230 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
231
232 // Set as default and try optionless methods
233 mapper.setDefaultGetOptions(Option.consistencyLevel(TWO));
234
235 try {
236 mapper.get(42);
237 fail("Expected a NoHostAvailableException");
238 } catch (NoHostAvailableException e) {
239 assertFirstNodeUnavailable(e);
240 }
241
242 try {
243 mapper.getAsync(42).get();
244 fail("Expected an ExecutionException");
245 } catch (ExecutionException e) {
246 assertFirstNodeUnavailable(e);
247 }
248
249 statement = mapper.getQuery(42);
250 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
251 }
252
253 @Test(groups = "short")
254 @CassandraVersion("2.0.0")
255 void should_use_delete_options_for_all_variants() throws InterruptedException {
256 User user = new User(42, "helloworld");
257
258 try {
259 mapper.delete(user, Option.consistencyLevel(TWO));
260 fail("Expected a NoHostAvailableException");
261 } catch (NoHostAvailableException e) {
262 assertFirstNodeUnavailable(e);
263 }
264
265 try {
266 mapper.deleteAsync(user, Option.consistencyLevel(TWO)).get();
267 fail("Expected an ExecutionException");
268 } catch (ExecutionException e) {
269 assertFirstNodeUnavailable(e);
270 }
271
272 Statement statement = mapper.deleteQuery(user, Option.consistencyLevel(TWO));
273 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
274
275 try {
276 mapper.delete(user.getKey(), Option.consistencyLevel(TWO));
277 fail("Expected a NoHostAvailableException");
278 } catch (NoHostAvailableException e) {
279 assertFirstNodeUnavailable(e);
280 }
281
282 try {
283 mapper.deleteAsync(user.getKey(), Option.consistencyLevel(TWO)).get();
284 fail("Expected an ExecutionException");
285 } catch (ExecutionException e) {
286 assertFirstNodeUnavailable(e);
287 }
288
289 statement = mapper.deleteQuery(user.getKey(), Option.consistencyLevel(TWO));
290 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
291
292 // Set as default and try optionless methods
293 mapper.setDefaultDeleteOptions(Option.consistencyLevel(TWO));
294
295 try {
296 mapper.delete(user);
297 fail("Expected a NoHostAvailableException");
298 } catch (NoHostAvailableException e) {
299 assertFirstNodeUnavailable(e);
300 }
301
302 try {
303 mapper.deleteAsync(user).get();
304 fail("Expected an ExecutionException");
305 } catch (ExecutionException e) {
306 assertFirstNodeUnavailable(e);
307 }
308
309 statement = mapper.deleteQuery(user);
310 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
311
312 try {
313 mapper.delete(user.getKey());
314 fail("Expected a NoHostAvailableException");
315 } catch (NoHostAvailableException e) {
316 assertFirstNodeUnavailable(e);
317 }
318
319 try {
320 mapper.deleteAsync(user.getKey()).get();
321 fail("Expected an ExecutionException");
322 } catch (ExecutionException e) {
323 assertFirstNodeUnavailable(e);
324 }
325
326 statement = mapper.deleteQuery(user.getKey());
327 assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
328 }
329
330 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
331 void should_fail_if_option_does_not_apply_to_query() {
332 mapper.get(42, Option.ttl(1));
333 }
334
335 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
336 void should_fail_when_using_ttl_with_protocol_v1() {
337 if (protocolVersion.compareTo(V1) > 0)
338 throw new SkipException("Skipped when protocol version > V1");
339
340 mapper.saveQuery(new User(42, "helloworld"), Option.ttl(15));
341 }
342
343 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
344 void should_fail_when_using_timestamp_with_protocol_v1() {
345 if (protocolVersion.compareTo(V1) > 0)
346 throw new SkipException("Skipped when protocol version > V1");
347
348 mapper.saveQuery(new User(42, "helloworld"), Option.timestamp(15));
349 }
350
351 private static void assertFirstNodeUnavailable(NoHostAvailableException e) {
352 Throwable node1Error = e.getErrors().values().iterator().next();
353 assertThat(node1Error).isInstanceOf(UnavailableException.class);
354 }
355
356 private static void assertFirstNodeUnavailable(ExecutionException e) {
357 Throwable cause = e.getCause();
358 assertThat(cause).isInstanceOf(NoHostAvailableException.class);
359 assertFirstNodeUnavailable((NoHostAvailableException) cause);
360 }
361
362 private static long futureTimestamp() {
363 return (System.currentTimeMillis() + 1000) * 1000;
364 }
365
366 @Table(name = "user", readConsistency = "LOCAL_ONE", writeConsistency = "ONE")
367 public static class User {
368 @PartitionKey
369 private int key;
370 private String v;
371
372 public User() {
373 }
374
375 public User(int k, String val) {
376 this.key = k;
377 this.v = val;
378 }
379
380 public int getKey() {
381 return this.key;
382 }
383
384 public void setKey(int pk) {
385 this.key = pk;
386 }
387
388 public String getV() {
389 return this.v;
390 }
391
392 public void setV(String val) {
393 this.v = val;
394 }
395 }
396}