Elffuss BraidHub

kikocis/java-driver public

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