Elffuss BraidHub

kikocis/java-driver public

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