Elffuss BraidHub

kikocis/java-driver public

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