Elffuss BraidHub

kikocis/java-driver public

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