Elffuss BraidHub

kikocis/java-driver public

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