Elffuss BraidHub

kikocis/java-driver public

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