Elffuss BraidHub

kikocis/java-driver public

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