Elffuss BraidHub

kikocis/java-driver public

cbe23d0de4cf · 18.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.utils.CassandraVersion;
20import com.datastax.driver.core.utils.UUIDs;
21import com.datastax.driver.mapping.annotations.*;
22import com.google.common.base.Objects;
23import com.google.common.util.concurrent.ListenableFuture;
24import org.testng.annotations.Test;
25
26import java.net.InetAddress;
27import java.util.Arrays;
28import java.util.HashSet;
29import java.util.Set;
30import java.util.UUID;
31
32import static org.assertj.core.api.Assertions.assertThat;
33import static org.testng.Assert.assertEquals;
34import static org.testng.Assert.assertTrue;
35
36/**
37 * Basic tests for the mapping module.
38 */
39@SuppressWarnings("unused")
40public class MapperTest extends CCMTestsSupport {
41
42 @Override
43 public void onTestContextInitialized() {
44 // We'll allow to generate those create statement from the annotated entities later, but it's currently
45 // a TODO
46 execute("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
47 "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
48 }
49
50 /*
51 * Annotates a simple entity. Not a whole lot to see here, all fields are
52 * mapped by default (but there is a @Transcient to have a field non mapped)
53 * to a C* column that have the same name than the field (but you can use @Column
54 * to specify the actual column name in C* if it's different).
55 *
56 * Do note that we support enums (which are mapped to strings by default
57 * but you can map them to their ordinal too with some @Enumerated annotation)
58 *
59 * And the next step will be to support UDT (which should be relatively simple).
60 */
61 @Table(name = "users",
62 readConsistency = "QUORUM",
63 writeConsistency = "QUORUM")
64 public static class User {
65
66 // Dummy constant to test that static fields are properly ignored
67 public static final int FOO = 1;
68
69 public enum Gender {FEMALE, MALE}
70
71 @PartitionKey
72 @Column(name = "user_id")
73 private UUID userId;
74
75 private String name;
76 private String email;
77 @Column // not strictly required, but we want to check that the annotation works without a name
78 private int year;
79
80 private Gender gender;
81
82 public User() {
83 }
84
85 public User(String name, String email, Gender gender) {
86 this.userId = UUIDs.random();
87 this.name = name;
88 this.email = email;
89 this.gender = gender;
90 }
91
92 public UUID getUserId() {
93 return userId;
94 }
95
96 public void setUserId(UUID userId) {
97 this.userId = userId;
98 }
99
100 public String getName() {
101 return name;
102 }
103
104 public void setName(String name) {
105 this.name = name;
106 }
107
108 public String getEmail() {
109 return email;
110 }
111
112 public void setEmail(String email) {
113 this.email = email;
114 }
115
116 public int getYear() {
117 return year;
118 }
119
120 public void setGender(Gender gender) {
121 this.gender = gender;
122 }
123
124 public Gender getGender() {
125 return gender;
126 }
127
128 public void setYear(int year) {
129 this.year = year;
130 }
131
132 @Override
133 public boolean equals(Object other) {
134 if (other == null || other.getClass() != this.getClass())
135 return false;
136
137 User that = (User) other;
138 return Objects.equal(userId, that.userId)
139 && Objects.equal(name, that.name)
140 && Objects.equal(email, that.email)
141 && Objects.equal(year, that.year)
142 && Objects.equal(gender, that.gender);
143 }
144
145 @Override
146 public int hashCode() {
147 return Objects.hashCode(userId, name, email, year, gender);
148 }
149 }
150
151 /*
152 * Another annotated entity, but that correspond to a table that has a
153 * clustering column. Note that if there is more than one clustering column,
154 * the order must be specified (@ClusteringColumn(0), @ClusteringColumn(1), ...).
155 * The same stands for the @PartitionKey.
156 */
157 @Table(name = "posts")
158 public static class Post {
159
160 private String title;
161 private String content;
162 private InetAddress device;
163
164 @ClusteringColumn
165 @Column(name = "post_id")
166 private UUID postId;
167
168 @PartitionKey
169 @Column(name = "user_id")
170 private UUID userId;
171
172
173 private Set<String> tags;
174
175 public Post() {
176 }
177
178 public Post(User user, String title) {
179 this.userId = user.getUserId();
180 this.postId = UUIDs.timeBased();
181 this.title = title;
182 }
183
184 public UUID getUserId() {
185 return userId;
186 }
187
188 public void setUserId(UUID userId) {
189 this.userId = userId;
190 }
191
192 public UUID getPostId() {
193 return postId;
194 }
195
196 public void setPostId(UUID postId) {
197 this.postId = postId;
198 }
199
200 public String getTitle() {
201 return title;
202 }
203
204 public void setTitle(String title) {
205 this.title = title;
206 }
207
208 public String getContent() {
209 return content;
210 }
211
212 public void setContent(String content) {
213 this.content = content;
214 }
215
216 public InetAddress getDevice() {
217 return device;
218 }
219
220 public void setDevice(InetAddress device) {
221 this.device = device;
222 }
223
224 public Set<String> getTags() {
225 return tags;
226 }
227
228 public void setTags(Set<String> tags) {
229 this.tags = tags;
230 }
231
232 @Override
233 public boolean equals(Object other) {
234 if (other == null || other.getClass() != this.getClass())
235 return false;
236
237 Post that = (Post) other;
238 return Objects.equal(userId, that.userId)
239 && Objects.equal(postId, that.postId)
240 && Objects.equal(title, that.title)
241 && Objects.equal(content, that.content)
242 && Objects.equal(device, that.device)
243 && Objects.equal(tags, that.tags);
244 }
245
246 @Override
247 public int hashCode() {
248 return Objects.hashCode(userId, postId, title, content, device, tags);
249 }
250 }
251
252 /*
253 * We actually have 2 concepts in the mapping module. The first is the
254 * mapping of entities like User and Post above. From such annotated entity
255 * you can get a Mapper object (see below), which allow to map the Row of
256 * ResultSet to proper object, and that provide a few simple method like
257 * save, delete and a simple get.
258 *
259 * But to remove a bit of boilerplate when you need more complex queries, we
260 * also have the concept of Accesor, which is just a way to associate some
261 * java method calls to queries. Note that you don't have to use those Accessor
262 * if you don't want (and in fact, you can use the Accessor concept even if
263 * you don't map any entity).
264 */
265 @Accessor
266 public interface PostAccessor {
267 // Note that for implementation reasons, this *needs* to be an interface.
268
269 // The @Param below is because you can't get the name of parameters of methods
270 // by reflection (you can only have their types), so you have to annotate them
271 // if you want to give them proper names in the query. That being said, if you
272 // don't have @Param annotation like in the 2 other method, we default to some
273 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
274 // somehow, but well, not a huge deal.
275 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
276 Post getOne(@Param("userId") UUID userId,
277 @Param("postId") UUID postId);
278
279 // Note that the following method will be asynchronous (it will use executeAsync
280 // underneath) because it's return type is a ListenableFuture. Similarly, we know
281 // that we need to map the result to the Post entity thanks to the return type.
282 @Query("SELECT * FROM posts WHERE user_id=?")
283 @QueryParameters(consistency = "QUORUM")
284 ListenableFuture<Result<Post>> getAllAsync(UUID userId);
285
286 // The method above actually query stuff, but if a method is declared to return
287 // a Statement, it will not execute anything, but just return you the BoundStatement
288 // ready for execution. That way, you can batch stuff for instance (see usage below).
289 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
290 Statement updateContentQuery(String newContent, UUID userId, UUID postId);
291
292 @Query("SELECT * FROM posts")
293 Result<Post> getAll();
294
295 @Query("SELECT * FROM posts")
296 @QueryParameters(idempotent = true)
297 Statement getAllAsStatementIdempotent();
298
299 @Query("SELECT * FROM posts")
300 @QueryParameters(idempotent = false)
301 Statement getAllAsStatementNonIdempotent();
302
303 @Query("SELECT * FROM posts")
304 Statement getAllAsStatement();
305 }
306
307 @Accessor
308 public interface UserAccessor {
309 // Demonstrates use of an enum as an accessor parameter
310 @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
311 ResultSet updateNameAndGender(String name, User.Gender gender, UUID userId);
312 }
313
314 @Test(groups = "short")
315 public void testStaticEntity() throws Exception {
316 // Very simple mapping a User, saving and getting it. Note that here we
317 // don't use the Accessor stuff since the queries we use are directly
318 // supported by the Mapper object.
319 Mapper<User> m = new MappingManager(session()).mapper(User.class);
320
321 User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
322 u1.setYear(2014);
323 m.save(u1);
324
325 // Do note that m.get() takes the primary key of what we want to fetch
326 // in argument, it doesn't not take a User object because we don't proxy
327 // objects `a la' SpringData/Hibernate. The reason for not doing that
328 // is that we don't want to encourage read-before-write.
329 assertEquals(m.get(u1.getUserId()), u1);
330 }
331
332 @Test(groups = "short")
333 @CassandraVersion(major = 2.0)
334 public void testDynamicEntity() throws Exception {
335 MappingManager manager = new MappingManager(session());
336
337 Mapper<Post> m = manager.mapper(Post.class);
338
339 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
340 Post p1 = new Post(u1, "Something about mapping");
341 Post p2 = new Post(u1, "Something else");
342 Post p3 = new Post(u1, "Something more");
343
344 p1.setDevice(InetAddress.getLocalHost());
345
346 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
347
348 m.save(p1);
349 m.save(p2);
350 m.save(p3);
351
352 // Creates the accessor proxy defined above
353 PostAccessor postAccessor = manager.createAccessor(PostAccessor.class);
354
355 // Note that getOne is really the same than m.get(), it's just there
356 // for demonstration sake.
357 Post p = postAccessor.getOne(p1.getUserId(), p1.getPostId());
358 assertEquals(p, p1);
359
360 Result<Post> r = postAccessor.getAllAsync(p1.getUserId()).get();
361 assertEquals(r.one(), p1);
362 assertEquals(r.one(), p2);
363 assertEquals(r.one(), p3);
364 assertTrue(r.isExhausted());
365
366 // No argument call
367 r = postAccessor.getAll();
368 assertEquals(r.one(), p1);
369 assertEquals(r.one(), p2);
370 assertEquals(r.one(), p3);
371 assertTrue(r.isExhausted());
372
373 BatchStatement batch = new BatchStatement();
374 batch.add(postAccessor.updateContentQuery("Something different", p1.getUserId(), p1.getPostId()));
375 batch.add(postAccessor.updateContentQuery("A different something", p2.getUserId(), p2.getPostId()));
376 manager.getSession().execute(batch);
377
378 Post p1New = m.get(p1.getUserId(), p1.getPostId());
379 assertEquals(p1New.getContent(), "Something different");
380 Post p2New = m.get(p2.getUserId(), p2.getPostId());
381 assertEquals(p2New.getContent(), "A different something");
382
383 m.delete(p1);
384 m.delete(p2);
385
386 // Check delete by primary key too
387 m.delete(p3.getUserId(), p3.getPostId());
388
389 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
390
391 // Pass an enum constant as an accessor parameter
392 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
393 userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
394 Mapper<User> userMapper = manager.mapper(User.class);
395 assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
396
397 // Test that an enum value can be unassigned through an accessor (set to null).
398 userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
399 assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
400 }
401
402 @Test(groups = "short")
403 public void should_map_objects_from_partial_queries() throws Exception {
404 MappingManager manager = new MappingManager(session());
405
406 Mapper<Post> m = manager.mapper(Post.class);
407
408 // Insert a few posts
409 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
410 Post p1 = new Post(u1, "Something about mapping");
411 Post p2 = new Post(u1, "Something else");
412 Post p3 = new Post(u1, "Something more");
413
414 p1.setDevice(InetAddress.getLocalHost());
415 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
416
417 m.save(p1);
418 m.save(p2);
419 m.save(p3);
420
421 // Retrieve posts with a projection query that only retrieves some of the fields
422 ResultSet rs = session().execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
423
424 Result<Post> result = m.map(rs);
425 for (Post post : result) {
426 assertThat(post.getUserId()).isEqualTo(u1.getUserId());
427 assertThat(post.getPostId()).isNotNull();
428 assertThat(post.getTitle()).isNotNull();
429
430 assertThat(post.getDevice()).isNull();
431 assertThat(post.getTags()).isNull();
432 }
433
434 // cleanup
435 session().execute("delete from posts where user_id = " + u1.getUserId());
436 }
437
438 @Test(groups = "short")
439 public void should_return_table_metadata() throws Exception {
440 MappingManager manager = new MappingManager(session());
441
442 Mapper<Post> m = manager.mapper(Post.class);
443
444 assertThat(m.getTableMetadata()).isNotNull();
445 assertThat(m.getTableMetadata().getName()).isEqualTo("posts");
446 assertThat(m.getTableMetadata().getPartitionKey()).hasSize(1);
447 }
448
449 @Test(groups = "short")
450 public void should_not_initialize_session_when_protocol_version_provided() {
451 Session newSession = cluster().newSession();
452
453 // Ensures that a Session is not initialized when a protocol version is provided.
454 MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
455 assertThat(newSession.getState().getConnectedHosts()).hasSize(0);
456
457 // Session should be initialized on first query.
458 newSession.execute("USE " + keyspace);
459 assertThat(newSession.getState().getConnectedHosts()).hasSize(1);
460 }
461
462 /**
463 * Ensures that if an accessor method has a {@link QueryParameters} annotation with
464 * {@link QueryParameters#idempotent()} as {@code true} that the {@link Statement} it generates returns
465 * {@code true} for {@link Statement#isIdempotent()}.
466 *
467 * @jira_ticket JAVA-923
468 * @test_category object_mapper
469 */
470 @Test(groups = "short")
471 public void should_flag_statement_as_idempotent() {
472 MappingManager manager = new MappingManager(session());
473 PostAccessor post = manager.createAccessor(PostAccessor.class);
474 Statement stmt = post.getAllAsStatementIdempotent();
475 assertThat(stmt.isIdempotent()).isEqualTo(true);
476 }
477
478 /**
479 * Ensures that if an accessor method has a {@link QueryParameters} annotation with
480 * {@link QueryParameters#idempotent()} as {@code false} that the {@link Statement} it generates returns
481 * {@code false} for {@link Statement#isIdempotent()}.
482 *
483 * @jira_ticket JAVA-923
484 * @test_category object_mapper
485 */
486 @Test(groups = "short")
487 public void should_flag_statement_as_non_idempotent() {
488 MappingManager manager = new MappingManager(session());
489 PostAccessor post = manager.createAccessor(PostAccessor.class);
490 Statement stmt = post.getAllAsStatementNonIdempotent();
491 assertThat(stmt.isIdempotent()).isEqualTo(false);
492 }
493
494 /**
495 * Ensures that if an accessor method lacks a {@link QueryParameters} annotation with
496 * {@link QueryParameters#idempotent()} set that the {@link Statement} it generates returns
497 * {@code null} for {@link Statement#isIdempotent()}.
498 *
499 * @jira_ticket JAVA-923
500 * @test_category object_mapper
501 */
502 @Test(groups = "short")
503 public void should_flag_statement_with_null_idempotence() {
504 MappingManager manager = new MappingManager(session());
505 PostAccessor post = manager.createAccessor(PostAccessor.class);
506 Statement stmt = post.getAllAsStatement();
507 assertThat(stmt.isIdempotent()).isNull();
508 }
509
510 /**
511 * Ensures that all statements generated by the mapper are
512 * flagged as idempotent.
513 *
514 * @jira_ticket JAVA-923
515 * @test_category object_mapper
516 */
517 @Test(groups = "short")
518 public void should_flag_all_mapper_generated_statements_as_idempotent() {
519 MappingManager manager = new MappingManager(session());
520 Mapper<User> mapper = manager.mapper(User.class);
521 User u = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
522 Statement saveQuery = mapper.saveQuery(u);
523 assertThat(saveQuery.isIdempotent()).isTrue();
524 Statement getQuery = mapper.getQuery(u.getUserId());
525 assertThat(saveQuery.isIdempotent()).isTrue();
526 Statement deleteQuery = mapper.deleteQuery(u.getUserId());
527 assertThat(saveQuery.isIdempotent()).isTrue();
528 }
529
530}