Elffuss BraidHub

kikocis/java-driver public

b0ad3785b703 · 15.0 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 java.util.Collection;
19import java.util.concurrent.ExecutionException;
20
21import com.google.common.collect.Lists;
22import org.testng.SkipException;
23import org.testng.annotations.BeforeMethod;
24import org.testng.annotations.Test;
25
26import static com.datastax.driver.core.ConsistencyLevel.*;
27import static org.assertj.core.api.Assertions.assertThat;
28import static org.assertj.core.api.Assertions.fail;
29
30import com.datastax.driver.core.*;
31import com.datastax.driver.core.exceptions.NoHostAvailableException;
32import com.datastax.driver.core.exceptions.UnavailableException;
33import com.datastax.driver.core.utils.CassandraVersion;
34import com.datastax.driver.mapping.annotations.PartitionKey;
35import com.datastax.driver.mapping.annotations.Table;
36
37import static com.datastax.driver.core.ProtocolVersion.V1;
38import static com.datastax.driver.mapping.Mapper.Option;
39
40public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster {
41
42 ProtocolVersion protocolVersion;
43 Mapper<User> mapper;
44
45 @Override
46 protected Collection<String> getTableDefinitions() {
47 return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)");
48 }
49
50 @BeforeMethod(groups = "short")
51 public void setup() {
52 mapper = new MappingManager(session).mapper(User.class);
53 protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
54 }
55
56 @Test(groups = "short")
57 @CassandraVersion(major = 2.0)
58 void should_use_save_options() throws Exception {
59 Long tsValue = futureTimestamp();
60 mapper.save(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
61 assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
62 Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
63 assertThat(tsReturned).isEqualTo(tsValue);
64 }
65
66 @Test(groups = "short")
67 @CassandraVersion(major = 2.0)
68 void should_use_delete_options() {
69 User todelete = new User(45, "todelete");
70 mapper.save(todelete);
71 Option opt = Option.timestamp(35);
72 BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
73 assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
74 assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
75 }
76
77 @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
78 @CassandraVersion(major = 2.0)
79 void should_use_get_options() {
80 User user = new User(45, "toget");
81 mapper.save(user);
82
83 BoundStatement bs = (BoundStatement)mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
84 assertThat(bs.isTracing()).isTrue();
85 assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
86
87 ResultSet rs = session.execute(bs);
88 assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
89 User us = mapper.mapAliased(rs).one();
90 assertThat(us.getV()).isEqualTo("toget");
91
92 mapper.getQuery(45, Option.timestamp(1337));
93 }
94
95 @Test(groups = "short")
96 @CassandraVersion(major = 2.0)
97 void should_use_options_only_once() {
98 Long tsValue = futureTimestamp();
99 mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
100 mapper.save(new User(44, "test"));
101 Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
102 // Assuming we cannot go back in time (yet) and execute the write at ts=1
103 assertThat(tsReturned).isNotEqualTo(tsValue);
104 }
105
106 @Test(groups = "short")
107 @CassandraVersion(major = 2.0)
108 void should_use_default_options() {
109 mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
110 BoundStatement bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"));
111 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
112
113 mapper.resetDefaultSaveOptions();
114 bs = (BoundStatement)mapper.saveQuery(new User(47, "rjhrgce"));
115 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
116
117 mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
118 bs = (BoundStatement)mapper.deleteQuery(47);
119 assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
120 assertThat(bs.isTracing()).isTrue();
121
122 mapper.resetDefaultDeleteOptions();
123 bs = (BoundStatement)mapper.deleteQuery(47);
124 assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
125 assertThat(bs.isTracing()).isFalse();
126
127 bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
128 assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
129
130 mapper.setDefaultGetOptions(Option.tracing(true));
131 bs = (BoundStatement)mapper.getQuery(46);
132 assertThat(bs.isTracing()).isTrue();
133
134 mapper.resetDefaultGetOptions();
135 bs = (BoundStatement)mapper.getQuery(46);
136 assertThat(bs.isTracing()).isFalse();
137 }
138
139 @Test(groups = "short")
140 @CassandraVersion(major = 2.0)
141 void should_prioritize_option_over_model_consistency() {
142 // Generate Write Query and ensure User model writeConsistency is used.
143 User user = new User(1859, "Steve");
144 Statement saveDefault = mapper.saveQuery(user);
145 assertThat(saveDefault.getConsistencyLevel()).isEqualTo(ONE);
146
147 // Generate Write Query and ensure provided Option for consistencyLevel is used.
148 Statement saveProvidedCL = mapper.saveQuery(user, Option.consistencyLevel(QUORUM));
149 assertThat(saveProvidedCL.getConsistencyLevel()).isEqualTo(QUORUM);
150
151 // Generate Read Query and ensure User model readConsistency is used.
152 Statement readDefault = mapper.getQuery(1859);
153 assertThat(readDefault.getConsistencyLevel()).isEqualTo(LOCAL_ONE);
154
155 // Generate Ready Query and ensure provided Option for consistencyLevel is used.
156 Statement readProvidedCL = mapper.getQuery(1859, Option.consistencyLevel(LOCAL_QUORUM));
157 assertThat(readProvidedCL.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
158 }
159
160 @Test(groups = "short")
161 @CassandraVersion(major = 2.0)
162 void should_use_explicit_options_over_default_options() {
163 long defaultTimestamp = futureTimestamp();
164 long explicitTimestamp = futureTimestamp();
165
166 mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
167
168 mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
169 Long savedTimestamp = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
170 assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
171 }
172
173 /** Cover all versions of save() to check that methods that call each other properly propagate the options */
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}