Elffuss BraidHub

kikocis/java-driver public

291b71942c66 · 15.7 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
296 @Accessor
297 public interface UserAccessor {
298 // Demonstrates use of an enum as an accessor parameter
299 @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
300 ResultSet updateNameAndGender(String name, User.Gender gender, UUID userId);
301 }
302
303 @Test(groups = "short")
304 public void testStaticEntity() throws Exception {
305 // Very simple mapping a User, saving and getting it. Note that here we
306 // don't use the Accessor stuff since the queries we use are directly
307 // supported by the Mapper object.
308 Mapper<User> m = new MappingManager(session()).mapper(User.class);
309
310 User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
311 u1.setYear(2014);
312 m.save(u1);
313
314 // Do note that m.get() takes the primary key of what we want to fetch
315 // in argument, it doesn't not take a User object because we don't proxy
316 // objects `a la' SpringData/Hibernate. The reason for not doing that
317 // is that we don't want to encourage read-before-write.
318 assertEquals(m.get(u1.getUserId()), u1);
319 }
320
321 @Test(groups = "short")
322 @CassandraVersion(major = 2.0)
323 public void testDynamicEntity() throws Exception {
324 MappingManager manager = new MappingManager(session());
325
326 Mapper<Post> m = manager.mapper(Post.class);
327
328 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
329 Post p1 = new Post(u1, "Something about mapping");
330 Post p2 = new Post(u1, "Something else");
331 Post p3 = new Post(u1, "Something more");
332
333 p1.setDevice(InetAddress.getLocalHost());
334
335 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
336
337 m.save(p1);
338 m.save(p2);
339 m.save(p3);
340
341 // Creates the accessor proxy defined above
342 PostAccessor postAccessor = manager.createAccessor(PostAccessor.class);
343
344 // Note that getOne is really the same than m.get(), it's just there
345 // for demonstration sake.
346 Post p = postAccessor.getOne(p1.getUserId(), p1.getPostId());
347 assertEquals(p, p1);
348
349 Result<Post> r = postAccessor.getAllAsync(p1.getUserId()).get();
350 assertEquals(r.one(), p1);
351 assertEquals(r.one(), p2);
352 assertEquals(r.one(), p3);
353 assertTrue(r.isExhausted());
354
355 // No argument call
356 r = postAccessor.getAll();
357 assertEquals(r.one(), p1);
358 assertEquals(r.one(), p2);
359 assertEquals(r.one(), p3);
360 assertTrue(r.isExhausted());
361
362 BatchStatement batch = new BatchStatement();
363 batch.add(postAccessor.updateContentQuery("Something different", p1.getUserId(), p1.getPostId()));
364 batch.add(postAccessor.updateContentQuery("A different something", p2.getUserId(), p2.getPostId()));
365 manager.getSession().execute(batch);
366
367 Post p1New = m.get(p1.getUserId(), p1.getPostId());
368 assertEquals(p1New.getContent(), "Something different");
369 Post p2New = m.get(p2.getUserId(), p2.getPostId());
370 assertEquals(p2New.getContent(), "A different something");
371
372 m.delete(p1);
373 m.delete(p2);
374
375 // Check delete by primary key too
376 m.delete(p3.getUserId(), p3.getPostId());
377
378 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
379
380 // Pass an enum constant as an accessor parameter
381 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
382 userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
383 Mapper<User> userMapper = manager.mapper(User.class);
384 assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
385
386 // Test that an enum value can be unassigned through an accessor (set to null).
387 userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
388 assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
389 }
390
391 @Test(groups = "short")
392 public void should_map_objects_from_partial_queries() throws Exception {
393 MappingManager manager = new MappingManager(session());
394
395 Mapper<Post> m = manager.mapper(Post.class);
396
397 // Insert a few posts
398 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
399 Post p1 = new Post(u1, "Something about mapping");
400 Post p2 = new Post(u1, "Something else");
401 Post p3 = new Post(u1, "Something more");
402
403 p1.setDevice(InetAddress.getLocalHost());
404 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
405
406 m.save(p1);
407 m.save(p2);
408 m.save(p3);
409
410 // Retrieve posts with a projection query that only retrieves some of the fields
411 ResultSet rs = session().execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
412
413 Result<Post> result = m.map(rs);
414 for (Post post : result) {
415 assertThat(post.getUserId()).isEqualTo(u1.getUserId());
416 assertThat(post.getPostId()).isNotNull();
417 assertThat(post.getTitle()).isNotNull();
418
419 assertThat(post.getDevice()).isNull();
420 assertThat(post.getTags()).isNull();
421 }
422
423 // cleanup
424 session().execute("delete from posts where user_id = " + u1.getUserId());
425 }
426
427 @Test(groups = "short")
428 public void should_return_table_metadata() throws Exception {
429 MappingManager manager = new MappingManager(session());
430
431 Mapper<Post> m = manager.mapper(Post.class);
432
433 assertThat(m.getTableMetadata()).isNotNull();
434 assertThat(m.getTableMetadata().getName()).isEqualTo("posts");
435 assertThat(m.getTableMetadata().getPartitionKey()).hasSize(1);
436 }
437
438 @Test(groups = "short")
439 public void should_not_initialize_session_when_protocol_version_provided() {
440 Session newSession = cluster().newSession();
441
442 // Ensures that a Session is not initialized when a protocol version is provided.
443 MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
444 assertThat(newSession.getState().getConnectedHosts()).hasSize(0);
445
446 // Session should be initialized on first query.
447 newSession.execute("USE " + keyspace);
448 assertThat(newSession.getState().getConnectedHosts()).hasSize(1);
449 }
450}