Elffuss BraidHub

kikocis/java-driver public

b1d245a67292 · 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 @PartitionKey
161 @Column(name = "user_id")
162 private UUID userId;
163
164 @ClusteringColumn
165 @Column(name = "post_id")
166 private UUID postId;
167
168 private String title;
169 private String content;
170 private InetAddress device;
171
172 private Set<String> tags;
173
174 public Post() {
175 }
176
177 public Post(User user, String title) {
178 this.userId = user.getUserId();
179 this.postId = UUIDs.timeBased();
180 this.title = title;
181 }
182
183 public UUID getUserId() {
184 return userId;
185 }
186
187 public void setUserId(UUID userId) {
188 this.userId = userId;
189 }
190
191 public UUID getPostId() {
192 return postId;
193 }
194
195 public void setPostId(UUID postId) {
196 this.postId = postId;
197 }
198
199 public String getTitle() {
200 return title;
201 }
202
203 public void setTitle(String title) {
204 this.title = title;
205 }
206
207 public String getContent() {
208 return content;
209 }
210
211 public void setContent(String content) {
212 this.content = content;
213 }
214
215 public InetAddress getDevice() {
216 return device;
217 }
218
219 public void setDevice(InetAddress device) {
220 this.device = device;
221 }
222
223 public Set<String> getTags() {
224 return tags;
225 }
226
227 public void setTags(Set<String> tags) {
228 this.tags = tags;
229 }
230
231 @Override
232 public boolean equals(Object other) {
233 if (other == null || other.getClass() != this.getClass())
234 return false;
235
236 Post that = (Post) other;
237 return Objects.equal(userId, that.userId)
238 && Objects.equal(postId, that.postId)
239 && Objects.equal(title, that.title)
240 && Objects.equal(content, that.content)
241 && Objects.equal(device, that.device)
242 && Objects.equal(tags, that.tags);
243 }
244
245 @Override
246 public int hashCode() {
247 return Objects.hashCode(userId, postId, title, content, device, tags);
248 }
249 }
250
251 /*
252 * We actually have 2 concepts in the mapping module. The first is the
253 * mapping of entities like User and Post above. From such annotated entity
254 * you can get a Mapper object (see below), which allow to map the Row of
255 * ResultSet to proper object, and that provide a few simple method like
256 * save, delete and a simple get.
257 *
258 * But to remove a bit of boilerplate when you need more complex queries, we
259 * also have the concept of Accesor, which is just a way to associate some
260 * java method calls to queries. Note that you don't have to use those Accessor
261 * if you don't want (and in fact, you can use the Accessor concept even if
262 * you don't map any entity).
263 */
264 @Accessor
265 public interface PostAccessor {
266 // Note that for implementation reasons, this *needs* to be an interface.
267
268 // The @Param below is because you can't get the name of parameters of methods
269 // by reflection (you can only have their types), so you have to annotate them
270 // if you want to give them proper names in the query. That being said, if you
271 // don't have @Param annotation like in the 2 other method, we default to some
272 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
273 // somehow, but well, not a huge deal.
274 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
275 Post getOne(@Param("userId") UUID userId,
276 @Param("postId") UUID postId);
277
278 // Note that the following method will be asynchronous (it will use executeAsync
279 // underneath) because it's return type is a ListenableFuture. Similarly, we know
280 // that we need to map the result to the Post entity thanks to the return type.
281 @Query("SELECT * FROM posts WHERE user_id=?")
282 @QueryParameters(consistency = "QUORUM")
283 ListenableFuture<Result<Post>> getAllAsync(UUID userId);
284
285 // The method above actually query stuff, but if a method is declared to return
286 // a Statement, it will not execute anything, but just return you the BoundStatement
287 // ready for execution. That way, you can batch stuff for instance (see usage below).
288 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
289 Statement updateContentQuery(String newContent, UUID userId, UUID postId);
290
291 @Query("SELECT * FROM posts")
292 Result<Post> getAll();
293 }
294
295 @Accessor
296 public interface UserAccessor {
297 // Demonstrates use of an enum as an accessor parameter
298 @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
299 ResultSet updateNameAndGender(String name, User.Gender gender, UUID userId);
300 }
301
302 @Test(groups = "short")
303 public void testStaticEntity() throws Exception {
304 // Very simple mapping a User, saving and getting it. Note that here we
305 // don't use the Accessor stuff since the queries we use are directly
306 // supported by the Mapper object.
307 Mapper<User> m = new MappingManager(session()).mapper(User.class);
308
309 User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
310 u1.setYear(2014);
311 m.save(u1);
312
313 // Do note that m.get() takes the primary key of what we want to fetch
314 // in argument, it doesn't not take a User object because we don't proxy
315 // objects `a la' SpringData/Hibernate. The reason for not doing that
316 // is that we don't want to encourage read-before-write.
317 assertEquals(m.get(u1.getUserId()), u1);
318 }
319
320 @Test(groups = "short")
321 @CassandraVersion(major = 2.0)
322 public void testDynamicEntity() throws Exception {
323 MappingManager manager = new MappingManager(session());
324
325 Mapper<Post> m = manager.mapper(Post.class);
326
327 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
328 Post p1 = new Post(u1, "Something about mapping");
329 Post p2 = new Post(u1, "Something else");
330 Post p3 = new Post(u1, "Something more");
331
332 p1.setDevice(InetAddress.getLocalHost());
333
334 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
335
336 m.save(p1);
337 m.save(p2);
338 m.save(p3);
339
340 // Creates the accessor proxy defined above
341 PostAccessor postAccessor = manager.createAccessor(PostAccessor.class);
342
343 // Note that getOne is really the same than m.get(), it's just there
344 // for demonstration sake.
345 Post p = postAccessor.getOne(p1.getUserId(), p1.getPostId());
346 assertEquals(p, p1);
347
348 Result<Post> r = postAccessor.getAllAsync(p1.getUserId()).get();
349 assertEquals(r.one(), p1);
350 assertEquals(r.one(), p2);
351 assertEquals(r.one(), p3);
352 assertTrue(r.isExhausted());
353
354 // No argument call
355 r = postAccessor.getAll();
356 assertEquals(r.one(), p1);
357 assertEquals(r.one(), p2);
358 assertEquals(r.one(), p3);
359 assertTrue(r.isExhausted());
360
361 BatchStatement batch = new BatchStatement();
362 batch.add(postAccessor.updateContentQuery("Something different", p1.getUserId(), p1.getPostId()));
363 batch.add(postAccessor.updateContentQuery("A different something", p2.getUserId(), p2.getPostId()));
364 manager.getSession().execute(batch);
365
366 Post p1New = m.get(p1.getUserId(), p1.getPostId());
367 assertEquals(p1New.getContent(), "Something different");
368 Post p2New = m.get(p2.getUserId(), p2.getPostId());
369 assertEquals(p2New.getContent(), "A different something");
370
371 m.delete(p1);
372 m.delete(p2);
373
374 // Check delete by primary key too
375 m.delete(p3.getUserId(), p3.getPostId());
376
377 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
378
379 // Pass an enum constant as an accessor parameter
380 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
381 userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
382 Mapper<User> userMapper = manager.mapper(User.class);
383 assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
384
385 // Test that an enum value can be unassigned through an accessor (set to null).
386 userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
387 assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
388 }
389
390 @Test(groups = "short")
391 public void should_map_objects_from_partial_queries() throws Exception {
392 MappingManager manager = new MappingManager(session());
393
394 Mapper<Post> m = manager.mapper(Post.class);
395
396 // Insert a few posts
397 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
398 Post p1 = new Post(u1, "Something about mapping");
399 Post p2 = new Post(u1, "Something else");
400 Post p3 = new Post(u1, "Something more");
401
402 p1.setDevice(InetAddress.getLocalHost());
403 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
404
405 m.save(p1);
406 m.save(p2);
407 m.save(p3);
408
409 // Retrieve posts with a projection query that only retrieves some of the fields
410 ResultSet rs = session().execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
411
412 Result<Post> result = m.map(rs);
413 for (Post post : result) {
414 assertThat(post.getUserId()).isEqualTo(u1.getUserId());
415 assertThat(post.getPostId()).isNotNull();
416 assertThat(post.getTitle()).isNotNull();
417
418 assertThat(post.getDevice()).isNull();
419 assertThat(post.getTags()).isNull();
420 }
421
422 // cleanup
423 session().execute("delete from posts where user_id = " + u1.getUserId());
424 }
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}