Elffuss BraidHub

kikocis/java-driver public

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