Elffuss BraidHub

kikocis/java-driver public

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