Elffuss BraidHub

kikocis/java-driver public

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