Elffuss BraidHub

kikocis/java-driver public

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