Elffuss BraidHub

kikocis/java-driver public

0d06ef6c86a5 · 17.0 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.util.Collections;
19import java.util.HashMap;
20import java.util.Map;
21
22import com.google.common.base.Function;
23import com.google.common.base.Functions;
24import com.google.common.util.concurrent.Futures;
25import com.google.common.util.concurrent.ListenableFuture;
26import org.slf4j.Logger;
27import org.slf4j.LoggerFactory;
28
29import com.datastax.driver.core.*;
30import com.datastax.driver.mapping.annotations.Accessor;
31import com.datastax.driver.mapping.annotations.Computed;
32
33/**
34 * An object handling the mapping of a particular class.
35 * <p>
36 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
37 * {@link MappingManager#mapper} method.
38 */
39public class Mapper<T> {
40
41 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
42
43 final MappingManager manager;
44 final ProtocolVersion protocolVersion;
45 final Class<T> klass;
46 final EntityMapper<T> mapper;
47 final TableMetadata tableMetadata;
48
49 // Cache prepared statements for each type of query we use.
50 private volatile Map<QueryType, PreparedStatement> preparedQueries = Collections.<QueryType, PreparedStatement>emptyMap();
51
52 private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
53
54 final Function<ResultSet, T> mapOneFunction;
55 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
56 final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
57
58 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
59 this.manager = manager;
60 this.klass = klass;
61 this.mapper = mapper;
62
63 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
64 this.tableMetadata = keyspace == null ? null : keyspace.getTable(Metadata.quote(mapper.getTable()));
65
66 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
67 this.mapOneFunction = new Function<ResultSet, T>() {
68 public T apply(ResultSet rs) {
69 return Mapper.this.mapAliased(rs).one();
70 }
71 };
72 this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
73 public T apply(ResultSet rs) {
74 return Mapper.this.map(rs).one();
75 }
76 };
77 this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
78 public Result<T> apply(ResultSet rs) {
79 return Mapper.this.map(rs);
80 }
81 };
82 }
83
84 Session session() {
85 return manager.getSession();
86 }
87
88 PreparedStatement getPreparedQuery(QueryType type) {
89 PreparedStatement stmt = preparedQueries.get(type);
90 if (stmt == null) {
91 synchronized (preparedQueries) {
92 stmt = preparedQueries.get(type);
93 if (stmt == null) {
94 String query = type.makePreparedQueryString(tableMetadata, mapper);
95 logger.debug("Preparing query {}", query);
96 stmt = session().prepare(query);
97 Map<QueryType, PreparedStatement> newQueries = new HashMap<QueryType, PreparedStatement>(preparedQueries);
98 newQueries.put(type, stmt);
99 preparedQueries = newQueries;
100 }
101 }
102 }
103 return stmt;
104 }
105
106 /**
107 * The {@code TableMetadata} for this mapper.
108 *
109 * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set.
110 */
111 public TableMetadata getTableMetadata() {
112 return tableMetadata;
113 }
114
115 /**
116 * The {@code MappingManager} managing this mapper.
117 *
118 * @return the {@code MappingManager} managing this mapper.
119 */
120 public MappingManager getManager() {
121 return manager;
122 }
123
124 /**
125 * Creates a query that can be used to save the provided entity.
126 * <p>
127 * This method is useful if you want to setup a number of options (tracing,
128 * conistency level, ...) of the returned statement before executing it manually
129 * or need access to the {@code ResultSet} object after execution (to get the
130 * trace, the execution info, ...), but in other cases, calling {@link #save}
131 * or {@link #saveAsync} is shorter.
132 *
133 * @param entity the entity to save.
134 * @return a query that saves {@code entity} (based on it's defined mapping).
135 */
136 public Statement saveQuery(T entity) {
137 PreparedStatement ps = getPreparedQuery(QueryType.SAVE);
138
139 BoundStatement bs = ps.bind();
140 int i = 0;
141 for (ColumnMapper<T> cm : mapper.allColumns()) {
142 if (cm.kind != ColumnMapper.Kind.COMPUTED) {
143 Object value = cm.getValue(entity);
144 bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
145 }
146 }
147
148 if (mapper.writeConsistency != null)
149 bs.setConsistencyLevel(mapper.writeConsistency);
150 return bs;
151 }
152
153 /**
154 * Save an entity mapped by this mapper.
155 * <p>
156 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
157 *
158 * @param entity the entity to save.
159 */
160 public void save(T entity) {
161 session().execute(saveQuery(entity));
162 }
163
164 /**
165 * Save an entity mapped by this mapper asynchonously.
166 * <p>
167 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
168 *
169 * @param entity the entity to save.
170 * @return a future on the completion of the save operation.
171 */
172 public ListenableFuture<Void> saveAsync(T entity) {
173 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
174 }
175
176 /**
177 * Creates a query that can be used to delete the provided entity.
178 * <p>
179 * This method is a shortcut that extract the PRIMARY KEY from the
180 * provided entity and call {@link #deleteQuery(Object...)} with it.
181 * <p>
182 * This method is useful if you want to setup a number of options (tracing,
183 * conistency level, ...) of the returned statement before executing it manually
184 * or need access to the {@code ResultSet} object after execution (to get the
185 * trace, the execution info, ...), but in other cases, calling {@link #delete}
186 * or {@link #deleteAsync} is shorter.
187 *
188 * @param entity the entity to delete.
189 * @return a query that delete {@code entity} (based on it's defined mapping).
190 */
191 public Statement deleteQuery(T entity) {
192 Object[] pks = new Object[mapper.primaryKeySize()];
193 for (int i = 0; i < pks.length; i++)
194 pks[i] = mapper.getPrimaryKeyColumn(i).getValue(entity);
195
196 return deleteQuery(pks);
197 }
198
199 /**
200 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
201 * <p>
202 * The values provided must correspond to the columns composing the PRIMARY
203 * KEY (in the order of said primary key).
204 * <p>
205 * This method is useful if you want to setup a number of options (tracing,
206 * conistency level, ...) of the returned statement before executing it manually
207 * or need access to the {@code ResultSet} object after execution (to get the
208 * trace, the execution info, ...), but in other cases, calling {@link #delete}
209 * or {@link #deleteAsync} is shorter.
210 *
211 * @param primaryKey the primary key of the entity to delete, or more precisely
212 * the values for the columns of said primary key in the order of the primary key.
213 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
214 *
215 * @throws IllegalArgumentException if the number of value provided differ from
216 * the number of columns composing the PRIMARY KEY of the mapped class, or if
217 * at least one of those values is {@code null}.
218 */
219 public Statement deleteQuery(Object...primaryKey) {
220 if (primaryKey.length != mapper.primaryKeySize())
221 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
222
223 PreparedStatement ps = getPreparedQuery(QueryType.DEL);
224
225 BoundStatement bs = ps.bind();
226 for (int i = 0; i < primaryKey.length; i++) {
227 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
228 Object value = primaryKey[i];
229 if (value == null)
230 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
231 bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
232 }
233
234 if (mapper.writeConsistency != null)
235 bs.setConsistencyLevel(mapper.writeConsistency);
236 return bs;
237 }
238
239 /**
240 * Deletes an entity mapped by this mapper.
241 * <p>
242 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}.
243 *
244 * @param entity the entity to delete.
245 */
246 public void delete(T entity) {
247 session().execute(deleteQuery(entity));
248 }
249
250 /**
251 * Deletes an entity mapped by this mapper asynchronously.
252 * <p>
253 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}.
254 *
255 * @param entity the entity to delete.
256 * @return a future on the completion of the deletion.
257 */
258 public ListenableFuture<Void> deleteAsync(T entity) {
259 return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
260 }
261
262 /**
263 * Deletes an entity based on its primary key.
264 * <p>
265 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(primaryKey))}.
266 *
267 * @param primaryKey the primary key of the entity to delete, or more precisely
268 * the values for the columns of said primary key in the order of the primary key.
269 *
270 * @throws IllegalArgumentException if the number of value provided differ from
271 * the number of columns composing the PRIMARY KEY of the mapped class, or if
272 * at least one of those values is {@code null}.
273 */
274 public void delete(Object... primaryKey) {
275 session().execute(deleteQuery(primaryKey));
276 }
277
278 /**
279 * Deletes an entity based on its primary key asynchronously.
280 * <p>
281 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(primaryKey))}.
282 *
283 * @param primaryKey the primary key of the entity to delete, or more precisely
284 * the values for the columns of said primary key in the order of the primary key.
285 * @return a future on the completion of the deletion.
286 *
287 * @throws IllegalArgumentException if the number of value provided differ from
288 * the number of columns composing the PRIMARY KEY of the mapped class, or if
289 * at least one of those values is {@code null}.
290 */
291 public ListenableFuture<Void> deleteAsync(Object... primaryKey) {
292 return Futures.transform(session().executeAsync(deleteQuery(primaryKey)), NOOP);
293 }
294
295 /**
296 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
297 * <p>
298 * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
299 * manual query or an {@link Accessor method}.
300 * It expects that the result set contains all column mapped in the target class,
301 * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
302 *
303 * @param resultSet the {@code ResultSet} to map.
304 * @return the mapped result set. Note that the returned mapped result set
305 * will encapsulate {@code resultSet} and so consuming results from this
306 * returned mapped result set will consume results from {@code resultSet}
307 * and vice-versa.
308 *
309 * @see #mapAliased(ResultSet)
310 */
311 public Result<T> map(ResultSet resultSet) {
312 return new Result<T>(resultSet, mapper, protocolVersion);
313 }
314
315 /**
316 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
317 * <p>
318 * Use this method to map a result set coming from the execution of the {@code Statement} returned by
319 * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
320 *
321 * @param resultSet the {@code ResultSet} to map.
322 * @return the mapped result set. Note that the returned mapped result set
323 * will encapsulate {@code resultSet} and so consuming results from this
324 * returned mapped result set will consume results from {@code resultSet}
325 * and vice-versa.
326 *
327 * @see #map(ResultSet)
328 */
329 public Result<T> mapAliased(ResultSet resultSet) {
330 return (manager.supportsAliases)
331 ? new Result<T>(resultSet, mapper, protocolVersion, true)
332 : map(resultSet);
333 }
334
335 /**
336 * Creates a query to fetch entity given its PRIMARY KEY.
337 * <p>
338 * The values provided must correspond to the columns composing the PRIMARY
339 * KEY (in the order of said primary key).
340 * <p>
341 * This method is useful if you want to setup a number of options (tracing,
342 * conistency level, ...) of the returned statement before executing it manually,
343 * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
344 *
345 * @param primaryKey the primary key of the entity to fetch, or more precisely
346 * the values for the columns of said primary key in the order of the primary key.
347 * @return a query that fetch the entity of PRIMARY KEY {@code primaryKey}.
348 *
349 * @throws IllegalArgumentException if the number of value provided differ from
350 * the number of columns composing the PRIMARY KEY of the mapped class, or if
351 * at least one of those values is {@code null}.
352 */
353 public Statement getQuery(Object... primaryKey) {
354 if (primaryKey.length != mapper.primaryKeySize())
355 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
356
357 PreparedStatement ps = getPreparedQuery(QueryType.GET);
358
359 BoundStatement bs = ps.bind();
360 for (int i = 0; i < primaryKey.length; i++) {
361 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
362 Object value = primaryKey[i];
363 if (value == null)
364 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
365 bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
366 }
367
368 if (mapper.readConsistency != null)
369 bs.setConsistencyLevel(mapper.readConsistency);
370 return bs;
371 }
372
373 /**
374 * Fetch an entity based on its primary key.
375 * <p>
376 * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(primaryKey))).one()}.
377 *
378 * @param primaryKey the primary key of the entity to fetch, or more precisely
379 * the values for the columns of said primary key in the order of the primary key.
380 * @return the entity fetched or {@code null} if it doesn't exist.
381 *
382 * @throws IllegalArgumentException if the number of value provided differ from
383 * the number of columns composing the PRIMARY KEY of the mapped class, or if
384 * at least one of those values is {@code null}.
385 */
386 public T get(Object... primaryKey) {
387 return mapAliased(session().execute(getQuery(primaryKey))).one();
388 }
389
390 /**
391 * Fetch an entity based on its primary key asynchronously.
392 * <p>
393 * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(primaryKey))}.
394 *
395 * @param primaryKey the primary key of the entity to fetch, or more precisely
396 * the values for the columns of said primary key in the order of the primary key.
397 * @return a future on the fetched entity. The return future will yield
398 * {@code null} if said entity doesn't exist.
399 *
400 * @throws IllegalArgumentException if the number of value provided differ from
401 * the number of columns composing the PRIMARY KEY of the mapped class, or if
402 * at least one of those values is {@code null}.
403 */
404 public ListenableFuture<T> getAsync(Object... primaryKey) {
405 return Futures.transform(session().executeAsync(getQuery(primaryKey)), mapOneFunction);
406 }
407}