Elffuss BraidHub

kikocis/java-driver public

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