Elffuss BraidHub

kikocis/java-driver public

6a5e82da7ff4 · 40.4 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import java.util.*;
19
20import com.google.common.base.Function;
21import com.google.common.base.Functions;
22import com.google.common.base.Objects;
23import com.google.common.base.Preconditions;
24import com.google.common.util.concurrent.Futures;
25import com.google.common.util.concurrent.ListenableFuture;
26import org.slf4j.Logger;
27import org.slf4j.LoggerFactory;
28
29import static com.google.common.base.Preconditions.checkArgument;
30
31import com.datastax.driver.core.*;
32import com.datastax.driver.core.querybuilder.Delete;
33import com.datastax.driver.core.querybuilder.Insert;
34import com.datastax.driver.core.querybuilder.QueryBuilder;
35import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
36import com.datastax.driver.mapping.annotations.Accessor;
37import com.datastax.driver.mapping.annotations.Computed;
38
39import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
40
41/**
42 * An object handling the mapping of a particular class.
43 * <p>
44 * A {@code Mapper} object is obtained from a {@code MappingManager} using the
45 * {@link MappingManager#mapper} method.
46 */
47public class Mapper<T> {
48
49 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
50
51 final MappingManager manager;
52 final ProtocolVersion protocolVersion;
53 final Class<T> klass;
54 final EntityMapper<T> mapper;
55 final TableMetadata tableMetadata;
56
57 // Cache prepared statements for each type of query we use.
58 private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
59
60 private static final Function<Object, Void> NOOP = Functions.constant(null);
61
62 private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
63 private volatile EnumMap<Option.Type, Option> defaultGetOptions;
64 private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
65
66 private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
67
68 final Function<ResultSet, T> mapOneFunction;
69 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
70 final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
71
72 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
73 this.manager = manager;
74 this.klass = klass;
75 this.mapper = mapper;
76
77 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
78 this.tableMetadata = keyspace == null ? null : keyspace.getTable(Metadata.quote(mapper.getTable()));
79
80 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
81 this.mapOneFunction = new Function<ResultSet, T>() {
82 public T apply(ResultSet rs) {
83 return Mapper.this.mapAliased(rs).one();
84 }
85 };
86 this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
87 public T apply(ResultSet rs) {
88 return Mapper.this.map(rs).one();
89 }
90 };
91 this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
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 = getPreparedQuery(QueryType.GET, options).bind();
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(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 mapAliased(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(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 * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
605 * manual query or an {@link Accessor method}.
606 * It expects that the result set contains all column mapped in the target class,
607 * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
608 *
609 * @param resultSet the {@code ResultSet} to map.
610 * @return the mapped result set. Note that the returned mapped result set
611 * will encapsulate {@code resultSet} and so consuming results from this
612 * returned mapped result set will consume results from {@code resultSet}
613 * and vice-versa.
614 *
615 * @see #mapAliased(ResultSet)
616 */
617 public Result<T> map(ResultSet resultSet) {
618 return new Result<T>(resultSet, mapper, protocolVersion);
619 }
620
621 /**
622 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
623 * <p>
624 * Use this method to map a result set coming from the execution of the {@code Statement} returned by
625 * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
626 *
627 * @param resultSet the {@code ResultSet} to map.
628 * @return the mapped result set. Note that the returned mapped result set
629 * will encapsulate {@code resultSet} and so consuming results from this
630 * returned mapped result set will consume results from {@code resultSet}
631 * and vice-versa.
632 *
633 * @see #map(ResultSet)
634 */
635 public Result<T> mapAliased(ResultSet resultSet) {
636 return (manager.isCassandraV1)
637 ? map(resultSet) // no aliases
638 : new Result<T>(resultSet, mapper, protocolVersion, true);
639 }
640
641 /**
642 * Set the default save {@link Option} for this object mapper, that will be used
643 * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
644 * to check available save options.
645 *
646 * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
647 */
648 public void setDefaultSaveOptions(Option... options) {
649 this.defaultSaveOptions = toMap(options);
650 }
651
652 /**
653 * Reset the default save options for this object mapper.
654 */
655 public void resetDefaultSaveOptions() {
656 this.defaultSaveOptions = NO_OPTIONS;
657 }
658
659 /**
660 * Set the default get {@link Option} for this object mapper, that will be used
661 * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
662 * get options.
663 *
664 * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
665 */
666 public void setDefaultGetOptions(Option... options) {
667 this.defaultGetOptions = toMap(options);
668
669 }
670
671 /**
672 * Reset the default save options for this object mapper.
673 */
674 public void resetDefaultGetOptions() {
675 this.defaultGetOptions = NO_OPTIONS;
676 }
677
678 /**
679 * Set the default delete {@link Option} for this object mapper, that will be used
680 * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
681 * to check available delete options.
682 *
683 * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
684 */
685 public void setDefaultDeleteOptions(Option... options) {
686 this.defaultDeleteOptions = toMap(options);
687 }
688
689 /**
690 * Reset the default delete options for this object mapper.
691 */
692 public void resetDefaultDeleteOptions() {
693 this.defaultDeleteOptions = NO_OPTIONS;
694 }
695
696 private static EnumMap<Option.Type, Option> toMap(Option[] options) {
697 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
698 for (Option option : options) {
699 result.put(option.type, option);
700 }
701 return result;
702 }
703
704 private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
705 EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
706 for (Option option : options) {
707 result.put(option.type, option);
708 }
709 return result;
710 }
711
712 /**
713 * An option for a mapper operation.
714 * <p>
715 * Options can be passed to individual operations:
716 * <pre>
717 * mapper.save(myObject, Option.ttl(3600));
718 * </pre>
719 *
720 * The mapper can also have defaults, that will apply to all operations that do not
721 * override these particular option:
722 * <pre>
723 * mapper.setDefaultSaveOptions(Option.ttl(3600));
724 * mapper.save(myObject);
725 * </pre>
726 *
727 * <p>
728 * See the static methods in this class for available options.
729 */
730 public static abstract class Option {
731
732 enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
733
734 final Type type;
735
736 protected Option(Type type) {
737 this.type = type;
738 }
739
740 /**
741 * Creates a new Option object to add time-to-live to a mapper operation. This is
742 * only valid for save operations.
743 * <p>
744 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
745 *
746 * @param ttl the TTL (in seconds).
747 * @return the option.
748 */
749 public static Option ttl(int ttl) {
750 return new Ttl(ttl);
751 }
752
753 /**
754 * Creates a new Option object to add a timestamp to a mapper operation. This is
755 * only valid for save and delete operations.
756 * <p>
757 * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
758 *
759 * @param timestamp the timestamp (in microseconds).
760 * @return the option.
761 */
762 public static Option timestamp(long timestamp) {
763 return new Timestamp(timestamp);
764 }
765
766 /**
767 * Creates a new Option object to add a consistency level value to a mapper operation. This
768 * is valid for save, delete and get operations.
769 * <p>
770 * Note that the consistency level can also be defined at the mapper level, as a parameter
771 * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
772 * for backward compatibility). This option, whether defined on a specific call or as the
773 * default, will always take precedence over the annotation.
774 *
775 * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
776 * @return the option.
777 */
778 public static Option consistencyLevel(ConsistencyLevel cl) {
779 return new ConsistencyLevelOption(cl);
780 }
781
782 /**
783 * Creates a new Option object to enable query tracing for a mapper operation. This
784 * is valid for save, delete and get operations.
785 *
786 * @param enabled whether to enable tracing.
787 * @return the option.
788 */
789 public static Option tracing(boolean enabled) {
790 return new Tracing(enabled);
791 }
792
793 /**
794 * Creates a new Option object to specify whether null entity fields should be included in
795 * insert queries. This option is valid only for save operations.
796 *
797 * If this option is not specified, it defaults to {@code true} (null fields are saved).
798 *
799 * @param enabled whether to include null fields in queries.
800 * @return the option.
801 */
802 public static Option saveNullFields(boolean enabled){
803 return new SaveNullFields(enabled);
804 }
805
806 public Type getType(){
807 return this.type;
808 }
809
810 abstract void appendTo(Insert.Options usings);
811
812 abstract void appendTo(Delete.Options usings);
813
814 abstract void addToPreparedStatement(BoundStatement bs, int i);
815
816 abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
817
818 abstract boolean isIncludedInQuery();
819
820 static class Ttl extends Option {
821
822 private int ttlValue;
823
824 Ttl(int value) {
825 super(Type.TTL);
826 this.ttlValue = value;
827 }
828
829 void appendTo(Insert.Options usings) {
830 usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
831 }
832 @Override
833 void appendTo(Delete.Options usings) {
834 throw new UnsupportedOperationException("shouldn't be called");
835 }
836 @Override
837 void addToPreparedStatement(BoundStatement bs, int i) {
838 bs.setInt(i, this.ttlValue);
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 @Override
846 boolean isIncludedInQuery() {
847 return true;
848 }
849 }
850
851 static class Timestamp extends Option {
852
853 private long tsValue;
854
855 Timestamp(long value) {
856 super(Type.TIMESTAMP);
857 this.tsValue = value;
858 }
859 @Override
860 void appendTo(Insert.Options usings) {
861 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
862 }
863 @Override
864 void appendTo(Delete.Options usings) {
865 usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
866 }
867 @Override
868 void checkValidFor(QueryType qt, MappingManager manager) {
869 checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
870 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
871 }
872 @Override
873 void addToPreparedStatement(BoundStatement bs, int i) {
874 bs.setLong(i, this.tsValue);
875 }
876 @Override
877 boolean isIncludedInQuery() {
878 return true;
879 }
880 }
881
882 static class ConsistencyLevelOption extends Option {
883
884 private ConsistencyLevel cl;
885
886 ConsistencyLevelOption(ConsistencyLevel cl) {
887 super(Type.CL);
888 this.cl = cl;
889 }
890 @Override
891 void appendTo(Insert.Options usings) {
892 throw new UnsupportedOperationException("shouldn't be called");
893 }
894 @Override
895 void appendTo(Delete.Options usings) {
896 throw new UnsupportedOperationException("shouldn't be called");
897 }
898
899 @Override
900 void addToPreparedStatement(BoundStatement bs, int i) {
901 bs.setConsistencyLevel(cl);
902 }
903 @Override
904 void checkValidFor(QueryType qt, MappingManager manager) {
905 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
906 "Consistency level option is only allowed in save, delete and get queries");
907 }
908
909 @Override
910 boolean isIncludedInQuery() {
911 return false;
912 }
913 }
914
915 static class Tracing extends Option {
916
917 private boolean tracing;
918
919 Tracing(boolean tracing) {
920 super(Type.TRACING);
921 this.tracing = tracing;
922 }
923 @Override
924 void appendTo(Insert.Options usings) {
925 throw new UnsupportedOperationException("shouldn't be called");
926 }
927 @Override
928 void appendTo(Delete.Options usings) {
929 throw new UnsupportedOperationException("shouldn't be called");
930 }
931
932 @Override
933 void addToPreparedStatement(BoundStatement bs, int i) {
934 if (this.tracing)
935 bs.enableTracing();
936 }
937
938 @Override
939 void checkValidFor(QueryType qt, MappingManager manager) {
940 checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
941 "Tracing option is only allowed in save, delete and get queries");
942 }
943
944 @Override
945 boolean isIncludedInQuery() {
946 return false;
947 }
948 }
949
950 static class SaveNullFields extends Option {
951
952 private boolean saveNullFields;
953
954 SaveNullFields(boolean saveNullFields) {
955 super(SAVE_NULL_FIELDS);
956 this.saveNullFields = saveNullFields;
957 }
958
959 @Override
960 void appendTo(Insert.Options usings) {
961 throw new UnsupportedOperationException("shouldn't be called");
962 }
963
964 @Override
965 void appendTo(Delete.Options usings) {
966 throw new UnsupportedOperationException("shouldn't be called");
967 }
968
969 @Override
970 void addToPreparedStatement(BoundStatement bs, int i) {
971 // nothing to do
972 }
973
974 @Override
975 void checkValidFor(QueryType qt, MappingManager manager) {
976 checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
977 }
978
979 @Override
980 boolean isIncludedInQuery() {
981 return false;
982 }
983 }
984
985 }
986
987 private static class MapperQueryKey {
988 private final QueryType queryType;
989 private final EnumSet<Option.Type> optionTypes;
990 private final Set<ColumnMapper<?>> columns;
991
992 MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
993 Preconditions.checkNotNull(queryType);
994 Preconditions.checkNotNull(options);
995 Preconditions.checkNotNull(columnMappers);
996 this.queryType = queryType;
997 this.columns = columnMappers;
998 this.optionTypes = EnumSet.noneOf(Option.Type.class);
999 for (Option opt : options.values()) {
1000 if (opt.isIncludedInQuery())
1001 this.optionTypes.add(opt.type);
1002 }
1003 }
1004
1005 @Override
1006 public boolean equals(Object other) {
1007 if (this == other)
1008 return true;
1009 if (other instanceof MapperQueryKey) {
1010 MapperQueryKey that = (MapperQueryKey)other;
1011 return this.queryType.equals(that.queryType)
1012 && this.optionTypes.equals(that.optionTypes)
1013 && this.columns.equals(that.columns);
1014 }
1015 return false;
1016 }
1017
1018 public int hashCode() {
1019 return Objects.hashCode(queryType, optionTypes, columns);
1020 }
1021 }
1022}