Elffuss BraidHub

kikocis/java-driver public

b4554bb54c38 · 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 java.net.InetAddress;
19
20import com.datastax.driver.core.utils.CassandraVersion;
21import com.datastax.driver.mapping.annotations.Table;
22import java.util.*;
23
24import com.google.common.base.Objects;
25import com.google.common.util.concurrent.ListenableFuture;
26import org.testng.annotations.Test;
27
28import static org.assertj.core.api.Assertions.assertThat;
29import static org.testng.Assert.*;
30
31import com.datastax.driver.mapping.annotations.*;
32import com.datastax.driver.core.*;
33import com.datastax.driver.core.utils.UUIDs;
34
35/**
36 * Basic tests for the mapping module.
37 */
38public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
39
40 @Override
41 protected Collection<String> getTableDefinitions() {
42 // We'll allow to generate those create statement from the annotated entities later, but it's currently
43 // a TODO
44 return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
45 "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
46 }
47
48 /*
49 * Annotates a simple entity. Not a whole lot to see here, all fields are
50 * mapped by default (but there is a @Transcient to have a field non mapped)
51 * to a C* column that have the same name than the field (but you can use @Column
52 * to specify the actual column name in C* if it's different).
53 *
54 * Do note that we support enums (which are mapped to strings by default
55 * but you can map them to their ordinal too with some @Enumerated annotation)
56 *
57 * And the next step will be to support UDT (which should be relatively simple).
58 */
59 @SuppressWarnings("unused")
60 @Table(name = "users",
61 readConsistency="QUORUM",
62 writeConsistency="QUORUM")
63 public static class User {
64
65 // Dummy constant to test that static fields are properly ignored
66 public static final int FOO = 1;
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 public User() {}
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 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}