Elffuss BraidHub

kikocis/java-driver public

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