Elffuss BraidHub

kikocis/java-driver public

66cf8d328fd5 · 40.6 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.querybuilder.Delete;
20import com.datastax.driver.core.querybuilder.Insert;
21import com.datastax.driver.core.querybuilder.QueryBuilder;
22import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
23import com.datastax.driver.mapping.annotations.Computed;
24import com.google.common.base.Function;
25import com.google.common.base.Functions;
26import com.google.common.base.Objects;
27import com.google.common.base.Preconditions;
28import com.google.common.util.concurrent.Futures;
29import com.google.common.util.concurrent.ListenableFuture;
30import org.slf4j.Logger;
31import org.slf4j.LoggerFactory;
32
33import java.util.*;
34
35import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
36import static com.google.common.base.Preconditions.checkArgument;
37
38/**
39 * An object handling the mapping of a particular class.
40 * <p/>
41 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
42 * {@link MappingManager#mapper} method.
43 */
44public class Mapper<T> {
45
46 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
47
48 final MappingManager manager;
49 final ProtocolVersion protocolVersion;
50 final Class<T> klass;
51 final EntityMapper<T> mapper;
52 final TableMetadata tableMetadata;
53
54 // Cache prepared statements for each type of query we use.
55 private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
56
57 private static final Function<Object, Void> NOOP = Functions.constant(null);
58
59 private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
60 private volatile EnumMap<Option.Type, Option> defaultGetOptions;
61 private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
62
63 private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
64
65 final Function<ResultSet, T> mapOneFunction;
66 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
67 final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
68
69 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
70 this.manager = manager;
71 this.klass = klass;
72 this.mapper = mapper;
73
74 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
75 this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable());
76
77 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
78 this.mapOneFunction = new Function<ResultSet, T>() {
79 @Override
80 public T apply(ResultSet rs) {
81 return Mapper.this.map(rs).one();
82 }
83 };
84 this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
85 @Override
86 public T apply(ResultSet rs) {
87 return Mapper.this.map(rs).one();
88 }
89 };
90 this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
91 @Override
92 public Result<T> apply(ResultSet rs) {
93 return Mapper.this.map(rs);
94 }
95 };
96
97 this.defaultSaveOptions = NO_OPTIONS;
98 this.defaultGetOptions = NO_OPTIONS;
99 this.defaultDeleteOptions = NO_OPTIONS;
100 }
101
102 Session session() {
103 return manager.getSession();
104 }
105
106 PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
107
108 MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
109
110 PreparedStatement stmt = preparedQueries.get(pqk);
111 if (stmt == null) {
112 synchronized (preparedQueries) {
113 stmt = preparedQueries.get(pqk);
114 if (stmt == null) {
115 String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
116 logger.debug("Preparing query {}", queryString);
117 stmt = session().prepare(queryString);
118 Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
119 newQueries.put(pqk, stmt);
120 preparedQueries = newQueries;
121 }
122 }
123 }
124 return stmt;
125 }
126
127 PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
128 return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
129 }
130
131 /**
132 * The {@code TableMetadata} for this mapper.
133 *
134 * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set.
135 */
136 public TableMetadata getTableMetadata() {
137 return tableMetadata;
138 }
139
140 /**
141 * The {@code MappingManager} managing this mapper.
142 *
143 * @return the {@code MappingManager} managing this mapper.
144 */
145 public MappingManager getManager() {
146 return manager;
147 }
148
149 /**
150 * Creates a query that can be used to save the provided entity.
151 * <p/>
152 * This method is useful if you want to setup a number of options (tracing,
153 * conistency level, ...) of the returned statement before executing it manually
154 * or need access to the {@code ResultSet} object after execution (to get the
155 * trace, the execution info, ...), but in other cases, calling {@link #save}
156 * or {@link #saveAsync} is shorter.
157 *
158 * @param entity the entity to save.
159 * @return a query that saves {@code entity} (based on it's defined mapping).
160 */
161 public Statement saveQuery(T entity) {
162 return saveQuery(entity, this.defaultSaveOptions);
163 }
164
165 /**
166 * Creates a query that can be used to save the provided entity.
167 * <p/>
168 * This method is useful if you want to setup a number of options (tracing,
169 * conistency level, ...) of the returned statement before executing it manually
170 * or need access to the {@code ResultSet} object after execution (to get the
171 * trace, the execution info, ...), but in other cases, calling {@link #save}
172 * or {@link #saveAsync} is shorter.
173 * This method allows you to provide a suite of {@link Option} to include in
174 * the SAVE query. Options currently supported for SAVE are :
175 * <ul>
176 * <li>Timestamp</li>
177 * <li>Time-to-live (ttl)</li>
178 * <li>Consistency level</li>
179 * <li>Tracing</li>
180 * </ul>
181 *
182 * @param entity the entity to save.
183 * @return a query that saves {@code entity} (based on it's defined mapping).
184 */
185 public Statement saveQuery(T entity, Option... options) {
186 return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
187 }
188
189 private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
190 Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
191 boolean saveNullFields = shouldSaveNullFields(options);
192
193 for (ColumnMapper<T> cm : mapper.allColumns()) {
194 Object value = cm.getValue(entity);
195 if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) {
196 values.put(cm, value);
197 }
198 }
199
200 BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
201 int i = 0;
202 for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
203 ColumnMapper<?> mapper = entry.getKey();
204 Object value = entry.getValue();
205 setObject(bs, i++, value, mapper);
206 }
207
208 if (mapper.writeConsistency != null)
209 bs.setConsistencyLevel(mapper.writeConsistency);
210
211 for (Option opt : options.values()) {
212 opt.checkValidFor(QueryType.SAVE, manager);
213 opt.addToPreparedStatement(bs, i++);
214 }
215
216 return bs;
217 }
218
219 private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
220 SaveNullFields option = (SaveNullFields) options.get(SAVE_NULL_FIELDS);
221 return option == null || option.saveNullFields;
222 }
223
224 private static void setObject(BoundStatement bs, int i, Object value, ColumnMapper<?> mapper) {
225 TypeCodec<Object> customCodec = mapper.getCustomCodec();
226 if (customCodec != null)
227 bs.set(i, value, customCodec);
228 else
229 bs.set(i, value, mapper.getJavaType());
230 }
231
232 /**
233 * Save an entity mapped by this mapper.
234 * <p/>
235 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
236 *
237 * @param entity the entity to save.
238 */
239 public void save(T entity) {
240 session().execute(saveQuery(entity));
241 }
242
243 /**
244 * Save an entity mapped by this mapper and using special options for save.
245 * This method allows you to provide a suite of {@link Option} to include in
246 * the SAVE query. Options currently supported for SAVE are :
247 * <ul>
248 * <li>Timestamp</li>
249 * <li>Time-to-live (ttl)</li>
250 * <li>Consistency level</li>
251 * <li>Tracing</li>
252 * </ul>
253 *
254 * @param entity the entity to save.
255 * @param options the options object specified defining special options when saving.
256 */
257 public void save(T entity, Option... options) {
258 session().execute(saveQuery(entity, options));
259 }
260
261 /**
262 * Save an entity mapped by this mapper asynchronously.
263 * <p/>
264 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
265 *
266 * @param entity the entity to save.
267 * @return a future on the completion of the save operation.
268 */
269 public ListenableFuture<Void> saveAsync(T entity) {
270 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
271 }
272
273 /**
274 * Save an entity mapped by this mapper asynchronously using special options for save.
275 * <p/>
276 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
277 *
278 * @param entity the entity to save.
279 * @param options the options object specified defining special options when saving.
280 * @return a future on the completion of the save operation.
281 */
282 public ListenableFuture<Void> saveAsync(T entity, Option... options) {
283 return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
284 }
285
286 /**
287 * Creates a query to fetch entity given its PRIMARY KEY.
288 * <p/>
289 * The values provided must correspond to the columns composing the PRIMARY
290 * KEY (in the order of said primary key).
291 * <p/>
292 * This method is useful if you want to setup a number of options (tracing,
293 * conistency level, ...) of the returned statement before executing it manually,
294 * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
295 * <p/>
296 * This method allows you to provide a suite of {@link Option} to include in
297 * the GET query. Options currently supported for GET are :
298 * <ul>
299 * <li>Consistency level</li>
300 * <li>Tracing</li>
301 * </ul>
302 *
303 * @param objects the primary key of the entity to fetch, or more precisely
304 * the values for the columns of said primary key in the order of the primary key.
305 * Can be followed by {@link Option} to include in the DELETE query.
306 * @return a query that fetch the entity of PRIMARY KEY {@code objects}.
307 * @throws IllegalArgumentException if the number of value provided differ from
308 * the number of columns composing the PRIMARY KEY of the mapped class, or if
309 * at least one of those values is {@code null}.
310 */
311 public Statement getQuery(Object... objects) {
312 // Order and duplicates matter for primary keys
313 List<Object> pks = new ArrayList<Object>();
314 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
315
316 for (Object o : objects) {
317 if (o instanceof Option) {
318 Option option = (Option) o;
319 options.put(option.type, option);
320 } else {
321 pks.add(o);
322 }
323 }
324 return getQuery(pks, options);
325 }
326
327 private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
328
329 if (primaryKeys.size() != mapper.primaryKeySize())
330 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
331
332 BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options));
333 int i = 0;
334 for (Object value : primaryKeys) {
335 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
336 if (value == null) {
337 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
338 }
339 setObject(bs, i++, value, column);
340 }
341
342 if (mapper.readConsistency != null)
343 bs.setConsistencyLevel(mapper.readConsistency);
344
345 for (Option opt : options.values()) {
346 opt.checkValidFor(QueryType.GET, manager);
347 opt.addToPreparedStatement(bs, i);
348 if (opt.isIncludedInQuery())
349 i++;
350 }
351
352 return bs;
353 }
354
355 /**
356 * Fetch an entity based on its primary key.
357 * <p/>
358 * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
359 *
360 * @param objects the primary key of the entity to fetch, or more precisely
361 * the values for the columns of said primary key in the order of the primary key.
362 * Can be followed by {@link Option} to include in the DELETE query.
363 * @return the entity fetched or {@code null} if it doesn't exist.
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 T get(Object... objects) {
369 return map(session().execute(getQuery(objects))).one();
370 }
371
372 /**
373 * Fetch an entity based on its primary key asynchronously.
374 * <p/>
375 * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
376 *
377 * @param objects the primary key of the entity to fetch, or more precisely
378 * the values for the columns of said primary key in the order of the primary key.
379 * Can be followed by {@link Option} to include in the DELETE query.
380 * @return a future on the fetched entity. The return future will yield
381 * {@code null} if said entity doesn't exist.
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 ListenableFuture<T> getAsync(Object... objects) {
387 return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
388 }
389
390 /**
391 * Creates a query that can be used to delete the provided entity.
392 * <p/>
393 * This method is a shortcut that extract the PRIMARY KEY from the
394 * provided entity and call {@link #deleteQuery(Object...)} with it.
395 * This method allows you to provide a suite of {@link Option} to include in
396 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
397 * is supported for DELETE queries.
398 * <p/>
399 * This method is useful if you want to setup a number of options (tracing,
400 * conistency level, ...) of the returned statement before executing it manually
401 * or need access to the {@code ResultSet} object after execution (to get the
402 * trace, the execution info, ...), but in other cases, calling {@link #delete}
403 * or {@link #deleteAsync} is shorter.
404 * <p/>
405 * This method allows you to provide a suite of {@link Option} to include in
406 * the DELETE query. Options currently supported for DELETE are :
407 * <ul>
408 * <li>Timestamp</li>
409 * <li>Consistency level</li>
410 * <li>Tracing</li>
411 * </ul>
412 *
413 * @param entity the entity to delete.
414 * @param options the options to add to the DELETE query.
415 * @return a query that delete {@code entity} (based on it's defined mapping) with
416 * provided USING options.
417 */
418 public Statement deleteQuery(T entity, Option... options) {
419 List<Object> pks = new ArrayList<Object>();
420 for (int i = 0; i < mapper.primaryKeySize(); i++) {
421 pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
422 }
423
424 return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
425 }
426
427 /**
428 * Creates a query that can be used to delete the provided entity.
429 * <p/>
430 * This method is a shortcut that extract the PRIMARY KEY from the
431 * provided entity and call {@link #deleteQuery(Object...)} with it.
432 * <p/>
433 * This method is useful if you want to setup a number of options (tracing,
434 * conistency level, ...) of the returned statement before executing it manually
435 * or need access to the {@code ResultSet} object after execution (to get the
436 * trace, the execution info, ...), but in other cases, calling {@link #delete}
437 * or {@link #deleteAsync} is shorter.
438 *
439 * @param entity the entity to delete.
440 * @return a query that delete {@code entity} (based on it's defined mapping).
441 */
442 public Statement deleteQuery(T entity) {
443 List<Object> pks = new ArrayList<Object>();
444 for (int i = 0; i < mapper.primaryKeySize(); i++) {
445 pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
446 }
447
448 return deleteQuery(pks, defaultDeleteOptions);
449 }
450
451 /**
452 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
453 * <p/>
454 * The values provided must correspond to the columns composing the PRIMARY
455 * KEY (in the order of said primary key). The values can also contain, after
456 * specifying the primary keys columns, a suite of {@link Option} to include in
457 * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
458 * is supported for DELETE queries.
459 * <p/>
460 * This method is useful if you want to setup a number of options (tracing,
461 * conistency level, ...) of the returned statement before executing it manually
462 * or need access to the {@code ResultSet} object after execution (to get the
463 * trace, the execution info, ...), but in other cases, calling {@link #delete}
464 * or {@link #deleteAsync} is shorter.
465 * This method allows you to provide a suite of {@link Option} to include in
466 * the DELETE query. Options currently supported for DELETE are :
467 * <ul>
468 * <li>Timestamp</li>
469 * <li>Consistency level</li>
470 * <li>Tracing</li>
471 * </ul>
472 *
473 * @param objects the primary key of the entity to delete, or more precisely
474 * the values for the columns of said primary key in the order of the primary key.
475 * Can be followed by {@link Option} to include in the DELETE
476 * query.
477 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
478 * @throws IllegalArgumentException if the number of value provided differ from
479 * the number of columns composing the PRIMARY KEY of the mapped class, or if
480 * at least one of those values is {@code null}.
481 */
482 public Statement deleteQuery(Object... objects) {
483 // Order and duplicates matter for primary keys
484 List<Object> pks = new ArrayList<Object>();
485 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
486
487 for (Object o : objects) {
488 if (o instanceof Option) {
489 Option option = (Option) o;
490 options.put(option.type, option);
491 } else {
492 pks.add(o);
493 }
494 }
495 return deleteQuery(pks, options);
496 }
497
498 private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
499 if (primaryKey.size() != mapper.primaryKeySize())
500 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
501
502 BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
503
504 if (mapper.writeConsistency != null)
505 bs.setConsistencyLevel(mapper.writeConsistency);
506
507 int i = 0;
508 for (Option opt : options.values()) {
509 opt.checkValidFor(QueryType.DEL, manager);
510 opt.addToPreparedStatement(bs, i);
511 if (opt.isIncludedInQuery())
512 i++;
513 }
514
515 int columnNumber = 0;
516 for (Object value : primaryKey) {
517 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
518 if (value == null) {
519 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
520 }
521 setObject(bs, i++, value, column);
522 columnNumber++;
523 }
524 return bs;
525 }
526
527 /**
528 * Deletes an entity mapped by this mapper.
529 * <p/>
530 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}.
531 *
532 * @param entity the entity to delete.
533 */
534 public void delete(T entity) {
535 session().execute(deleteQuery(entity));
536 }
537
538 /**
539 * Deletes an entity mapped by this mapper using provided options.
540 * <p/>
541 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
542 *
543 * @param entity the entity to delete.
544 * @param options the options to add to the DELETE query.
545 */
546 public void delete(T entity, Option... options) {
547 session().execute(deleteQuery(entity, options));
548 }
549
550 /**
551 * Deletes an entity mapped by this mapper asynchronously.
552 * <p/>
553 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}.
554 *
555 * @param entity the entity to delete.
556 * @return a future on the completion of the deletion.
557 */
558 public ListenableFuture<Void> deleteAsync(T entity) {
559 return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
560 }
561
562 /**
563 * Deletes an entity mapped by this mapper asynchronously using provided options.
564 * <p/>
565 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
566 *
567 * @param entity the entity to delete.
568 * @param options the options to add to the DELETE query.
569 * @return a future on the completion of the deletion.
570 */
571 public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
572 return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
573 }
574
575 /**
576 * Deletes an entity based on its primary key.
577 * <p/>
578 * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
579 *
580 * @param objects the primary key of the entity to delete, or more precisely
581 * the values for the columns of said primary key in the order
582 * of the primary key.Can be followed by {@link Option} to include
583 * in the DELETE query.
584 * @throws IllegalArgumentException if the number of value provided differ from
585 * the number of columns composing the PRIMARY KEY of the mapped class, or if
586 * at least one of those values is {@code null}.
587 */
588 public void delete(Object... objects) {
589 session().execute(deleteQuery(objects));
590 }
591
592 /**
593 * Deletes an entity based on its primary key asynchronously.
594 * <p/>
595 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
596 *
597 * @param objects the primary key of the entity to delete, or more precisely
598 * the values for the columns of said primary key in the order
599 * of the primary key. Can be followed by {@link Option} to include
600 * in the DELETE query.
601 * @throws IllegalArgumentException if the number of value provided differ from
602 * the number of columns composing the PRIMARY KEY of the mapped class, or if
603 * at least one of those values is {@code null}.
604 */
605 public ListenableFuture<Void> deleteAsync(Object... objects) {
606 return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
607 }
608
609 /**
610 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
611 * <p/>
612 * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with
613 * {@link com.datastax.driver.mapping.annotations.Query @Query} in an
614 * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns
615 * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be
616 * populated.
617 * <p/>
618 * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be
619 * mapped, as if the object came from a direct {@link #get(Object...)} call.
620 *
621 * @param resultSet the {@code ResultSet} to map.
622 * @return the mapped result set. Note that the returned mapped result set
623 * will encapsulate {@code resultSet} and so consuming results from this
624 * returned mapped result set will consume results from {@code resultSet}
625 * and vice-versa.
626 */
627 public Result<T> map(ResultSet resultSet) {
628 boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet);
629 return new Result<T>(resultSet, mapper, protocolVersion, useAlias);
630 }
631
632 private boolean isFromMapperQuery(ResultSet resultSet) {
633 return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement;
634 }
635
636 /**
637 * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use
638 * {@link #map(ResultSet)} instead of this method.
639 */
640 @Deprecated
641 public Result<T> mapAliased(ResultSet resultSet) {
642 return map(resultSet);
643 }
644
645 /**
646 * Set the default save {@link Option} for this object mapper, that will be used
647 * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
648 * to check available save options.
649 *
650 * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
651 */
652 public void setDefaultSaveOptions(Option... options) {
653 this.defaultSaveOptions = toMap(options);
654 }
655
656 /**
657 * Reset the default save options for this object mapper.
658 */
659 public void resetDefaultSaveOptions() {
660 this.defaultSaveOptions = NO_OPTIONS;
661 }
662
663 /**
664 * Set the default get {@link Option} for this object mapper, that will be used
665 * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
666 * get options.
667 *
668 * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
669 */
670 public void setDefaultGetOptions(Option... options) {
671 this.defaultGetOptions = toMap(options);
672
673 }
674
675 /**
676 * Reset the default save options for this object mapper.
677 */
678 public void resetDefaultGetOptions() {
679 this.defaultGetOptions = NO_OPTIONS;
680 }
681
682 /**
683 * Set the default delete {@link Option} for this object mapper, that will be used
684 * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
685 * to check available delete options.
686 *
687 * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
688 */
689 public void setDefaultDeleteOptions(Option... options) {
690 this.defaultDeleteOptions = toMap(options);
691 }
692
693 /**
694 * Reset the default delete options for this object mapper.
695 */
696 public void resetDefaultDeleteOptions() {
697 this.defaultDeleteOptions = NO_OPTIONS;
698 }
699
700 private static EnumMap<Option.Type, Option> toMap(Option[] options) {
701 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
702 for (Option option : options) {
703 result.put(option.type, option);
704 }
705 return result;
706 }
707
708 private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
709 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
710 for (Option option : options) {
711 result.put(option.type, option);
712 }
713 return result;
714 }
715
716 /**
717 * An option for a mapper operation.
718 * <p/>
719 * Options can be passed to individual operations:
720 * <pre>
721 * mapper.save(myObject, Option.ttl(3600));
722 * </pre>
723 * <p/>
724 * The mapper can also have defaults, that will apply to all operations that do not
725 * override these particular option:
726 * <pre>
727 * mapper.setDefaultSaveOptions(Option.ttl(3600));
728 * mapper.save(myObject);
729 * </pre>
730 * <p/>
731 * <p/>
732 * See the static methods in this class for available options.
733 */
734 public static abstract class Option {
735
736 enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
737
738 final Type type;
739
740 protected Option(Type type) {
741 this.type = type;
742 }
743
744 /**
745 * Creates a new Option object to add time-to-live to a mapper operation. This is
746 * only valid for save operations.
747 * <p/>
748 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
749 *
750 * @param ttl the TTL (in seconds).
751 * @return the option.
752 */
753 public static Option ttl(int ttl) {
754 return new Ttl(ttl);
755 }
756
757 /**
758 * Creates a new Option object to add a timestamp to a mapper operation. This is
759 * only valid for save and delete operations.
760 * <p/>
761 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
762 *
763 * @param timestamp the timestamp (in microseconds).
764 * @return the option.
765 */
766 public static Option timestamp(long timestamp) {
767 return new Timestamp(timestamp);
768 }
769
770 /**
771 * Creates a new Option object to add a consistency level value to a mapper operation. This
772 * is valid for save, delete and get operations.
773 * <p/>
774 * Note that the consistency level can also be defined at the mapper level, as a parameter
775 * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
776 * for backward compatibility). This option, whether defined on a specific call or as the
777 * default, will always take precedence over the annotation.
778 *
779 * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
780 * @return the option.
781 */
782 public static Option consistencyLevel(ConsistencyLevel cl) {
783 return new ConsistencyLevelOption(cl);
784 }
785
786 /**
787 * Creates a new Option object to enable query tracing for a mapper operation. This
788 * is valid for save, delete and get operations.
789 *
790 * @param enabled whether to enable tracing.
791 * @return the option.
792 */
793 public static Option tracing(boolean enabled) {
794 return new Tracing(enabled);
795 }
796
797 /**
798 * Creates a new Option object to specify whether null entity fields should be included in
799 * insert queries. This option is valid only for save operations.
800 * <p/>
801 * If this option is not specified, it defaults to {@code true} (null fields are saved).
802 *
803 * @param enabled whether to include null fields in queries.
804 * @return the option.
805 */
806 public static Option saveNullFields(boolean enabled) {
807 return new SaveNullFields(enabled);
808 }
809
810 public Type getType() {
811 return this.type;
812 }
813
814 abstract void appendTo(Insert.Options usings);
815
816 abstract void appendTo(Delete.Options usings);
817
818 abstract void addToPreparedStatement(BoundStatement bs, int i);
819
820 abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
821
822 abstract boolean isIncludedInQuery();
823
824 static class Ttl extends Option {
825
826 private int ttlValue;
827
828 Ttl(int value) {
829 super(Type.TTL);
830 this.ttlValue = value;
831 }
832
833 @Override
834 void appendTo(Insert.Options usings) {
835 usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
836 }
837
838 @Override
839 void appendTo(Delete.Options usings) {
840 throw new UnsupportedOperationException("shouldn't be called");
841 }
842
843 @Override
844 void addToPreparedStatement(BoundStatement bs, int i) {
845 bs.setInt(i, this.ttlValue);
846 }
847
848 @Override
849 void checkValidFor(QueryType qt, MappingManager manager) {
850 checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
851 checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
852 }
853
854 @Override
855 boolean isIncludedInQuery() {
856 return true;
857 }
858 }
859
860 static class Timestamp extends Option {
861
862 private long tsValue;
863
864 Timestamp(long value) {
865 super(Type.TIMESTAMP);
866 this.tsValue = value;
867 }
868
869 @Override
870 void appendTo(Insert.Options usings) {
871 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
872 }
873
874 @Override
875 void appendTo(Delete.Options usings) {
876 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
877 }
878
879 @Override
880 void checkValidFor(QueryType qt, MappingManager manager) {
881 checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
882 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
883 }
884
885 @Override
886 void addToPreparedStatement(BoundStatement bs, int i) {
887 bs.setLong(i, this.tsValue);
888 }
889
890 @Override
891 boolean isIncludedInQuery() {
892 return true;
893 }
894 }
895
896 static class ConsistencyLevelOption extends Option {
897
898 private ConsistencyLevel cl;
899
900 ConsistencyLevelOption(ConsistencyLevel cl) {
901 super(Type.CL);
902 this.cl = cl;
903 }
904
905 @Override
906 void appendTo(Insert.Options usings) {
907 throw new UnsupportedOperationException("shouldn't be called");
908 }
909
910 @Override
911 void appendTo(Delete.Options usings) {
912 throw new UnsupportedOperationException("shouldn't be called");
913 }
914
915 @Override
916 void addToPreparedStatement(BoundStatement bs, int i) {
917 bs.setConsistencyLevel(cl);
918 }
919
920 @Override
921 void checkValidFor(QueryType qt, MappingManager manager) {
922 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
923 "Consistency level option is only allowed in save, delete and get queries");
924 }
925
926 @Override
927 boolean isIncludedInQuery() {
928 return false;
929 }
930 }
931
932 static class Tracing extends Option {
933
934 private boolean tracing;
935
936 Tracing(boolean tracing) {
937 super(Type.TRACING);
938 this.tracing = tracing;
939 }
940
941 @Override
942 void appendTo(Insert.Options usings) {
943 throw new UnsupportedOperationException("shouldn't be called");
944 }
945
946 @Override
947 void appendTo(Delete.Options usings) {
948 throw new UnsupportedOperationException("shouldn't be called");
949 }
950
951 @Override
952 void addToPreparedStatement(BoundStatement bs, int i) {
953 if (this.tracing)
954 bs.enableTracing();
955 }
956
957 @Override
958 void checkValidFor(QueryType qt, MappingManager manager) {
959 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
960 "Tracing option is only allowed in save, delete and get queries");
961 }
962
963 @Override
964 boolean isIncludedInQuery() {
965 return false;
966 }
967 }
968
969 static class SaveNullFields extends Option {
970
971 private boolean saveNullFields;
972
973 SaveNullFields(boolean saveNullFields) {
974 super(SAVE_NULL_FIELDS);
975 this.saveNullFields = saveNullFields;
976 }
977
978 @Override
979 void appendTo(Insert.Options usings) {
980 throw new UnsupportedOperationException("shouldn't be called");
981 }
982
983 @Override
984 void appendTo(Delete.Options usings) {
985 throw new UnsupportedOperationException("shouldn't be called");
986 }
987
988 @Override
989 void addToPreparedStatement(BoundStatement bs, int i) {
990 // nothing to do
991 }
992
993 @Override
994 void checkValidFor(QueryType qt, MappingManager manager) {
995 checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
996 }
997
998 @Override
999 boolean isIncludedInQuery() {
1000 return false;
1001 }
1002 }
1003
1004 }
1005
1006 private static class MapperQueryKey {
1007 private final QueryType queryType;
1008 private final EnumSet<Option.Type> optionTypes;
1009 private final Set<ColumnMapper<?>> columns;
1010
1011 MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
1012 Preconditions.checkNotNull(queryType);
1013 Preconditions.checkNotNull(options);
1014 Preconditions.checkNotNull(columnMappers);
1015 this.queryType = queryType;
1016 this.columns = columnMappers;
1017 this.optionTypes = EnumSet.noneOf(Option.Type.class);
1018 for (Option opt : options.values()) {
1019 if (opt.isIncludedInQuery())
1020 this.optionTypes.add(opt.type);
1021 }
1022 }
1023
1024 @Override
1025 public boolean equals(Object other) {
1026 if (this == other)
1027 return true;
1028 if (other instanceof MapperQueryKey) {
1029 MapperQueryKey that = (MapperQueryKey) other;
1030 return this.queryType.equals(that.queryType)
1031 && this.optionTypes.equals(that.optionTypes)
1032 && this.columns.equals(that.columns);
1033 }
1034 return false;
1035 }
1036
1037 @Override
1038 public int hashCode() {
1039 return Objects.hashCode(queryType, optionTypes, columns);
1040 }
1041 }
1042}