Elffuss BraidHub

kikocis/java-driver public

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