Elffuss BraidHub

kikocis/java-driver public

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