Elffuss BraidHub

kikocis/java-driver public

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