Elffuss BraidHub

kikocis/java-driver public

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