Elffuss BraidHub

kikocis/java-driver public

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