Elffuss BraidHub

kikocis/java-driver public

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