Elffuss BraidHub

kikocis/java-driver public

JAVA-477 : Add USING options in mapper for delete and save operations
Changeset22494c9e09ae6aaa11b6bc4f0c9cbaf069888ce8fa445e51320606da138617ad
AuthorKevin Gallardo <kevin.gallardo@datastax.com> · 2015-05-22 10:37 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-07-01 15:18 +02:00
Parents835cbb4c43e6

Browse the files at this changeset

10 files changed

modified changelog/README.md +2 −0
@@ -19,6 +19,8 @@
1919 - [improvement] Use same pool implementation for protocol v2 and v3
2020 (JAVA-738).
2121 - [improvement] Support CONTAINS / CONTAINS KEY in QueryBuilder (JAVA-677)
22+- [improvement] Add USING options in mapper for delete and save
23+ operations (JAVA-477/JAVA-540)
2224
2325 Merged from 2.0 branch:
2426
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +11 −0
@@ -136,6 +136,17 @@
136136 return usings.and(using);
137137 }
138138
139+ /**
140+ * Returns the options for this DELETE statement.
141+ * <p/>
142+ * Chain this with {@link Options#and(Using)} to add options.
143+ *
144+ * @return the options of this DELETE statement.
145+ */
146+ public Options using() {
147+ return usings;
148+ }
149+
139150 /**
140151 * Sets the 'IF EXISTS' option for this DELETE statement.
141152 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +10 −0
@@ -134,6 +134,16 @@
134134 return usings.and(using);
135135 }
136136
137+ /**
138+ * Returns the options for this INSERT statement.
139+ * <p/>
140+ * Chain this with {@link Options#and(Using)} to add options.
141+ *
142+ * @return the options of this INSERT statement.
143+ */
144+ public Options using() {
145+ return usings;
146+ }
137147 /**
138148 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
139149 * <p>
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +2 −3
@@ -27,7 +27,6 @@
2727 import com.google.common.base.Strings;
2828
2929 import com.datastax.driver.core.ConsistencyLevel;
30-import com.datastax.driver.core.ProtocolVersion;
3130 import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
3231 import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper;
3332 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
@@ -76,7 +75,7 @@
7675 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
7776 continue;
7877
79- if (!mappingManager.supportsAliases && field.getAnnotation(Computed.class) != null)
78+ if (mappingManager.isCassandraV1 && field.getAnnotation(Computed.class) != null)
8079 throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
8180
8281 AnnotationChecks.validateAnnotations(field, "entity",
@@ -99,7 +98,7 @@
9998 }
10099 }
101100
102- AtomicInteger columnCounter = mappingManager.supportsAliases ? new AtomicInteger(0) : null;
101+ AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
103102
104103 Collections.sort(pks, fieldComparator);
105104 Collections.sort(ccs, fieldComparator);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +649 −112
@@ -15,18 +15,23 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collections;
19-import java.util.HashMap;
20-import java.util.Map;
18+import java.util.*;
2119
2220 import com.google.common.base.Function;
2321 import com.google.common.base.Functions;
22+import com.google.common.base.Objects;
23+import com.google.common.base.Preconditions;
2424 import com.google.common.util.concurrent.Futures;
2525 import com.google.common.util.concurrent.ListenableFuture;
2626 import org.slf4j.Logger;
2727 import org.slf4j.LoggerFactory;
2828
29+import static com.google.common.base.Preconditions.checkArgument;
30+
2931 import com.datastax.driver.core.*;
32+import com.datastax.driver.core.querybuilder.Delete;
33+import com.datastax.driver.core.querybuilder.Insert;
34+import com.datastax.driver.core.querybuilder.QueryBuilder;
3035 import com.datastax.driver.mapping.annotations.Accessor;
3136 import com.datastax.driver.mapping.annotations.Computed;
3237
@@ -47,9 +52,15 @@
4752 final TableMetadata tableMetadata;
4853
4954 // Cache prepared statements for each type of query we use.
50- private volatile Map<QueryType, PreparedStatement> preparedQueries = Collections.<QueryType, PreparedStatement>emptyMap();
55+ private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
56+
57+ private static final Function<Object, Void> NOOP = Functions.constant(null);
5158
52- private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
59+ private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
60+ private volatile EnumMap<Option.Type, Option> defaultGetOptions;
61+ private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
62+
63+ private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
5364
5465 final Function<ResultSet, T> mapOneFunction;
5566 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
@@ -79,23 +90,30 @@
7990 return Mapper.this.map(rs);
8091 }
8192 };
93+
94+ this.defaultSaveOptions = NO_OPTIONS;
95+ this.defaultGetOptions = NO_OPTIONS;
96+ this.defaultDeleteOptions = NO_OPTIONS;
8297 }
8398
8499 Session session() {
85100 return manager.getSession();
86101 }
87102
88- PreparedStatement getPreparedQuery(QueryType type) {
89- PreparedStatement stmt = preparedQueries.get(type);
103+ PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
104+
105+ MapperQueryKey pqk = new MapperQueryKey(type, options);
106+
107+ PreparedStatement stmt = preparedQueries.get(pqk);
90108 if (stmt == null) {
91109 synchronized (preparedQueries) {
92- stmt = preparedQueries.get(type);
110+ stmt = preparedQueries.get(pqk);
93111 if (stmt == null) {
94- String query = type.makePreparedQueryString(tableMetadata, mapper);
95- logger.debug("Preparing query {}", query);
96- stmt = session().prepare(query);
97- Map<QueryType, PreparedStatement> newQueries = new HashMap<QueryType, PreparedStatement>(preparedQueries);
98- newQueries.put(type, stmt);
112+ String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, options.values());
113+ logger.debug("Preparing query {}", queryString);
114+ stmt = session().prepare(queryString);
115+ Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
116+ newQueries.put(pqk, stmt);
99117 preparedQueries = newQueries;
100118 }
101119 }
@@ -134,9 +152,35 @@
134152 * @return a query that saves {@code entity} (based on it's defined mapping).
135153 */
136154 public Statement saveQuery(T entity) {
137- PreparedStatement ps = getPreparedQuery(QueryType.SAVE);
155+ return saveQuery(entity, this.defaultSaveOptions);
156+ }
157+
158+ /**
159+ * Creates a query that can be used to save the provided entity.
160+ * <p>
161+ * This method is useful if you want to setup a number of options (tracing,
162+ * conistency level, ...) of the returned statement before executing it manually
163+ * or need access to the {@code ResultSet} object after execution (to get the
164+ * trace, the execution info, ...), but in other cases, calling {@link #save}
165+ * or {@link #saveAsync} is shorter.
166+ * This method allows you to provide a suite of {@link Option} to include in
167+ * the SAVE query. Options currently supported for SAVE are :
168+ * <ul>
169+ * <li>Timestamp</li>
170+ * <li>Time-to-live (ttl)</li>
171+ * <li>Consistency level</li>
172+ * <li>Tracing</li>
173+ * </ul>
174+ *
175+ * @param entity the entity to save.
176+ * @return a query that saves {@code entity} (based on it's defined mapping).
177+ */
178+ public Statement saveQuery(T entity, Option... options) {
179+ return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
180+ }
138181
139- BoundStatement bs = ps.bind();
182+ private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
183+ BoundStatement bs = getPreparedQuery(QueryType.SAVE, options).bind();
140184 int i = 0;
141185 for (ColumnMapper<T> cm : mapper.allColumns()) {
142186 if (cm.kind != ColumnMapper.Kind.COMPUTED) {
@@ -147,6 +191,12 @@
147191
148192 if (mapper.writeConsistency != null)
149193 bs.setConsistencyLevel(mapper.writeConsistency);
194+
195+ for (Option opt : options.values()) {
196+ opt.checkValidFor(QueryType.SAVE, manager);
197+ opt.addToPreparedStatement(bs, i++);
198+ }
199+
150200 return bs;
151201 }
152202
@@ -162,7 +212,25 @@
162212 }
163213
164214 /**
165- * Save an entity mapped by this mapper asynchonously.
215+ * Save an entity mapped by this mapper and using special options for save.
216+ * This method allows you to provide a suite of {@link Option} to include in
217+ * the SAVE query. Options currently supported for SAVE are :
218+ * <ul>
219+ * <li>Timestamp</li>
220+ * <li>Time-to-live (ttl)</li>
221+ * <li>Consistency level</li>
222+ * <li>Tracing</li>
223+ * </ul>
224+ *
225+ * @param entity the entity to save.
226+ * @param options the options object specified defining special options when saving.
227+ */
228+ public void save(T entity, Option... options) {
229+ session().execute(saveQuery(entity, options));
230+ }
231+
232+ /**
233+ * Save an entity mapped by this mapper asynchronously.
166234 * <p>
167235 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
168236 *
@@ -173,6 +241,161 @@
173241 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
174242 }
175243
244+ /**
245+ * Save an entity mapped by this mapper asynchronously using special options for save.
246+ * <p>
247+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
248+ *
249+ * @param entity the entity to save.
250+ * @param options the options object specified defining special options when saving.
251+ * @return a future on the completion of the save operation.
252+ */
253+ public ListenableFuture<Void> saveAsync(T entity, Option... options) {
254+ return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
255+ }
256+
257+ /**
258+ * Creates a query to fetch entity given its PRIMARY KEY.
259+ * <p>
260+ * The values provided must correspond to the columns composing the PRIMARY
261+ * KEY (in the order of said primary key).
262+ * <p>
263+ * This method is useful if you want to setup a number of options (tracing,
264+ * conistency level, ...) of the returned statement before executing it manually,
265+ * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
266+ * <p>
267+ * This method allows you to provide a suite of {@link Option} to include in
268+ * the GET query. Options currently supported for GET are :
269+ * <ul>
270+ * <li>Consistency level</li>
271+ * <li>Tracing</li>
272+ * </ul>
273+ *
274+ * @param objects the primary key of the entity to fetch, or more precisely
275+ * the values for the columns of said primary key in the order of the primary key.
276+ * Can be followed by {@link Option} to include in the DELETE query.
277+ * @return a query that fetch the entity of PRIMARY KEY {@code objects}.
278+ * @throws IllegalArgumentException if the number of value provided differ from
279+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
280+ * at least one of those values is {@code null}.
281+ */
282+ public Statement getQuery(Object... objects) {
283+ // Order and duplicates matter for primary keys
284+ List<Object> pks = new ArrayList<Object>();
285+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
286+
287+ for (Object o : objects) {
288+ if (o instanceof Option) {
289+ Option option = (Option)o;
290+ options.put(option.type, option);
291+ } else {
292+ pks.add(o);
293+ }
294+ }
295+ return getQuery(pks, options);
296+ }
297+
298+ private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
299+
300+ if (primaryKeys.size() != mapper.primaryKeySize())
301+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
302+
303+ BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
304+ int i = 0;
305+ for (Object value : primaryKeys) {
306+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
307+ if (value == null) {
308+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
309+ }
310+ bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
311+ i++;
312+ }
313+
314+ if (mapper.readConsistency != null)
315+ bs.setConsistencyLevel(mapper.readConsistency);
316+
317+ for (Option opt : options.values()) {
318+ opt.checkValidFor(QueryType.GET, manager);
319+ opt.addToPreparedStatement(bs, i);
320+ if (opt.isIncludedInQuery())
321+ i++;
322+ }
323+
324+ return bs;
325+ }
326+
327+ /**
328+ * Fetch an entity based on its primary key.
329+ * <p>
330+ * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
331+ *
332+ * @param objects the primary key of the entity to fetch, or more precisely
333+ * the values for the columns of said primary key in the order of the primary key.
334+ * Can be followed by {@link Option} to include in the DELETE query.
335+ * @return the entity fetched or {@code null} if it doesn't exist.
336+ * @throws IllegalArgumentException if the number of value provided differ from
337+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
338+ * at least one of those values is {@code null}.
339+ */
340+ public T get(Object... objects) {
341+ return mapAliased(session().execute(getQuery(objects))).one();
342+ }
343+
344+ /**
345+ * Fetch an entity based on its primary key asynchronously.
346+ * <p>
347+ * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
348+ *
349+ * @param objects the primary key of the entity to fetch, or more precisely
350+ * the values for the columns of said primary key in the order of the primary key.
351+ * Can be followed by {@link Option} to include in the DELETE query.
352+ * @return a future on the fetched entity. The return future will yield
353+ * {@code null} if said entity doesn't exist.
354+ * @throws IllegalArgumentException if the number of value provided differ from
355+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
356+ * at least one of those values is {@code null}.
357+ */
358+ public ListenableFuture<T> getAsync(Object... objects) {
359+ return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
360+ }
361+
362+ /**
363+ * Creates a query that can be used to delete the provided entity.
364+ * <p>
365+ * This method is a shortcut that extract the PRIMARY KEY from the
366+ * provided entity and call {@link #deleteQuery(Object...)} with it.
367+ * This method allows you to provide a suite of {@link Option} to include in
368+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
369+ * is supported for DELETE queries.
370+ * <p>
371+ * This method is useful if you want to setup a number of options (tracing,
372+ * conistency level, ...) of the returned statement before executing it manually
373+ * or need access to the {@code ResultSet} object after execution (to get the
374+ * trace, the execution info, ...), but in other cases, calling {@link #delete}
375+ * or {@link #deleteAsync} is shorter.
376+ * <p>
377+ * This method allows you to provide a suite of {@link Option} to include in
378+ * the DELETE query. Options currently supported for DELETE are :
379+ * <ul>
380+ * <li>Timestamp</li>
381+ * <li>Consistency level</li>
382+ * <li>Tracing</li>
383+ * </ul>
384+ *
385+ * @param entity the entity to delete.
386+ * @param options the options to add to the DELETE query.
387+ * @return a query that delete {@code entity} (based on it's defined mapping) with
388+ * provided USING options.
389+ */
390+ public Statement deleteQuery(T entity, Option... options) {
391+ List<Object> pks = new ArrayList<Object>();
392+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
393+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
394+ }
395+
396+ return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
397+ }
398+
176399 /**
177400 * Creates a query that can be used to delete the provided entity.
178401 * <p>
@@ -189,50 +412,87 @@
189412 * @return a query that delete {@code entity} (based on it's defined mapping).
190413 */
191414 public Statement deleteQuery(T entity) {
192- Object[] pks = new Object[mapper.primaryKeySize()];
193- for (int i = 0; i < pks.length; i++)
194- pks[i] = mapper.getPrimaryKeyColumn(i).getValue(entity);
415+ List<Object> pks = new ArrayList<Object>();
416+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
417+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
418+ }
195419
196- return deleteQuery(pks);
420+ return deleteQuery(pks, defaultDeleteOptions);
197421 }
198422
199423 /**
200424 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
201425 * <p>
202426 * The values provided must correspond to the columns composing the PRIMARY
203- * KEY (in the order of said primary key).
427+ * KEY (in the order of said primary key). The values can also contain, after
428+ * specifying the primary keys columns, a suite of {@link Option} to include in
429+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
430+ * is supported for DELETE queries.
204431 * <p>
205432 * This method is useful if you want to setup a number of options (tracing,
206433 * conistency level, ...) of the returned statement before executing it manually
207434 * or need access to the {@code ResultSet} object after execution (to get the
208435 * trace, the execution info, ...), but in other cases, calling {@link #delete}
209436 * or {@link #deleteAsync} is shorter.
437+ * This method allows you to provide a suite of {@link Option} to include in
438+ * the DELETE query. Options currently supported for DELETE are :
439+ * <ul>
440+ * <li>Timestamp</li>
441+ * <li>Consistency level</li>
442+ * <li>Tracing</li>
443+ * </ul>
210444 *
211- * @param primaryKey the primary key of the entity to delete, or more precisely
212- * the values for the columns of said primary key in the order of the primary key.
445+ * @param objects the primary key of the entity to delete, or more precisely
446+ * the values for the columns of said primary key in the order of the primary key.
447+ * Can be followed by {@link Option} to include in the DELETE
448+ * query.
213449 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
214- *
215450 * @throws IllegalArgumentException if the number of value provided differ from
216- * the number of columns composing the PRIMARY KEY of the mapped class, or if
217- * at least one of those values is {@code null}.
451+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
452+ * at least one of those values is {@code null}.
218453 */
219- public Statement deleteQuery(Object...primaryKey) {
220- if (primaryKey.length != mapper.primaryKeySize())
221- throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
454+ public Statement deleteQuery(Object... objects) {
455+ // Order and duplicates matter for primary keys
456+ List<Object> pks = new ArrayList<Object>();
457+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
458+
459+ for (Object o : objects) {
460+ if (o instanceof Option) {
461+ Option option = (Option)o;
462+ options.put(option.type, option);
463+ } else {
464+ pks.add(o);
465+ }
466+ }
467+ return deleteQuery(pks, options);
468+ }
222469
223- PreparedStatement ps = getPreparedQuery(QueryType.DEL);
470+ private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
471+ if (primaryKey.size() != mapper.primaryKeySize())
472+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
224473
225- BoundStatement bs = ps.bind();
226- for (int i = 0; i < primaryKey.length; i++) {
227- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
228- Object value = primaryKey[i];
229- if (value == null)
230- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
231- bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
232- }
474+ BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
233475
234476 if (mapper.writeConsistency != null)
235477 bs.setConsistencyLevel(mapper.writeConsistency);
478+
479+ int i = 0;
480+ for (Option opt : options.values()) {
481+ opt.checkValidFor(QueryType.DEL, manager);
482+ opt.addToPreparedStatement(bs, i);
483+ if (opt.isIncludedInQuery())
484+ i++;
485+ }
486+
487+ int columnNumber = 0;
488+ for (Object value : primaryKey) {
489+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
490+ if (value == null) {
491+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
492+ }
493+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
494+ columnNumber++;
495+ }
236496 return bs;
237497 }
238498
@@ -247,6 +507,18 @@
247507 session().execute(deleteQuery(entity));
248508 }
249509
510+ /**
511+ * Deletes an entity mapped by this mapper using provided options.
512+ * <p>
513+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
514+ *
515+ * @param entity the entity to delete.
516+ * @param options the options to add to the DELETE query.
517+ */
518+ public void delete(T entity, Option... options) {
519+ session().execute(deleteQuery(entity, options));
520+ }
521+
250522 /**
251523 * Deletes an entity mapped by this mapper asynchronously.
252524 * <p>
@@ -260,36 +532,50 @@
260532 }
261533
262534 /**
263- * Deletes an entity based on its primary key.
535+ * Deletes an entity mapped by this mapper asynchronously using provided options.
264536 * <p>
265- * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(primaryKey))}.
537+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
266538 *
267- * @param primaryKey the primary key of the entity to delete, or more precisely
268- * the values for the columns of said primary key in the order of the primary key.
539+ * @param entity the entity to delete.
540+ * @param options the options to add to the DELETE query.
541+ * @return a future on the completion of the deletion.
542+ */
543+ public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
544+ return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
545+ }
546+
547+ /**
548+ * Deletes an entity based on its primary key.
549+ * <p>
550+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
269551 *
552+ * @param objects the primary key of the entity to delete, or more precisely
553+ * the values for the columns of said primary key in the order
554+ * of the primary key.Can be followed by {@link Option} to include
555+ * in the DELETE query.
270556 * @throws IllegalArgumentException if the number of value provided differ from
271- * the number of columns composing the PRIMARY KEY of the mapped class, or if
272- * at least one of those values is {@code null}.
557+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
558+ * at least one of those values is {@code null}.
273559 */
274- public void delete(Object... primaryKey) {
275- session().execute(deleteQuery(primaryKey));
560+ public void delete(Object... objects) {
561+ session().execute(deleteQuery(objects));
276562 }
277563
278564 /**
279565 * Deletes an entity based on its primary key asynchronously.
280566 * <p>
281- * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(primaryKey))}.
282- *
283- * @param primaryKey the primary key of the entity to delete, or more precisely
284- * the values for the columns of said primary key in the order of the primary key.
285- * @return a future on the completion of the deletion.
567+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
286568 *
569+ * @param objects the primary key of the entity to delete, or more precisely
570+ * the values for the columns of said primary key in the order
571+ * of the primary key. Can be followed by {@link Option} to include
572+ * in the DELETE query.
287573 * @throws IllegalArgumentException if the number of value provided differ from
288- * the number of columns composing the PRIMARY KEY of the mapped class, or if
289- * at least one of those values is {@code null}.
574+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
575+ * at least one of those values is {@code null}.
290576 */
291- public ListenableFuture<Void> deleteAsync(Object... primaryKey) {
292- return Futures.transform(session().executeAsync(deleteQuery(primaryKey)), NOOP);
577+ public ListenableFuture<Void> deleteAsync(Object... objects) {
578+ return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
293579 }
294580
295581 /**
@@ -327,81 +613,332 @@
327613 * @see #map(ResultSet)
328614 */
329615 public Result<T> mapAliased(ResultSet resultSet) {
330- return (manager.supportsAliases)
331- ? new Result<T>(resultSet, mapper, protocolVersion, true)
332- : map(resultSet);
616+ return (manager.isCassandraV1)
617+ ? map(resultSet) // no aliases
618+ : new Result<T>(resultSet, mapper, protocolVersion, true);
333619 }
334620
335621 /**
336- * Creates a query to fetch entity given its PRIMARY KEY.
337- * <p>
338- * The values provided must correspond to the columns composing the PRIMARY
339- * KEY (in the order of said primary key).
340- * <p>
341- * This method is useful if you want to setup a number of options (tracing,
342- * conistency level, ...) of the returned statement before executing it manually,
343- * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
622+ * Set the default save {@link Option} for this object mapper, that will be used
623+ * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
624+ * to check available save options.
344625 *
345- * @param primaryKey the primary key of the entity to fetch, or more precisely
346- * the values for the columns of said primary key in the order of the primary key.
347- * @return a query that fetch the entity of PRIMARY KEY {@code primaryKey}.
348- *
349- * @throws IllegalArgumentException if the number of value provided differ from
350- * the number of columns composing the PRIMARY KEY of the mapped class, or if
351- * at least one of those values is {@code null}.
626+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
352627 */
353- public Statement getQuery(Object... primaryKey) {
354- if (primaryKey.length != mapper.primaryKeySize())
355- throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
628+ public void setDefaultSaveOptions(Option... options) {
629+ this.defaultSaveOptions = toMap(options);
630+ }
356631
357- PreparedStatement ps = getPreparedQuery(QueryType.GET);
632+ /**
633+ * Reset the default save options for this object mapper.
634+ */
635+ public void resetDefaultSaveOptions() {
636+ this.defaultSaveOptions = NO_OPTIONS;
637+ }
358638
359- BoundStatement bs = ps.bind();
360- for (int i = 0; i < primaryKey.length; i++) {
361- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
362- Object value = primaryKey[i];
363- if (value == null)
364- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
365- bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
366- }
639+ /**
640+ * Set the default get {@link Option} for this object mapper, that will be used
641+ * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
642+ * get options.
643+ *
644+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
645+ */
646+ public void setDefaultGetOptions(Option... options) {
647+ this.defaultGetOptions = toMap(options);
367648
368- if (mapper.readConsistency != null)
369- bs.setConsistencyLevel(mapper.readConsistency);
370- return bs;
371649 }
372650
373651 /**
374- * Fetch an entity based on its primary key.
375- * <p>
376- * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(primaryKey))).one()}.
377- *
378- * @param primaryKey the primary key of the entity to fetch, or more precisely
379- * the values for the columns of said primary key in the order of the primary key.
380- * @return the entity fetched or {@code null} if it doesn't exist.
652+ * Reset the default save options for this object mapper.
653+ */
654+ public void resetDefaultGetOptions() {
655+ this.defaultGetOptions = NO_OPTIONS;
656+ }
657+
658+ /**
659+ * Set the default delete {@link Option} for this object mapper, that will be used
660+ * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
661+ * to check available delete options.
381662 *
382- * @throws IllegalArgumentException if the number of value provided differ from
383- * the number of columns composing the PRIMARY KEY of the mapped class, or if
384- * at least one of those values is {@code null}.
663+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
385664 */
386- public T get(Object... primaryKey) {
387- return mapAliased(session().execute(getQuery(primaryKey))).one();
665+ public void setDefaultDeleteOptions(Option... options) {
666+ this.defaultDeleteOptions = toMap(options);
388667 }
389668
390669 /**
391- * Fetch an entity based on its primary key asynchronously.
670+ * Reset the default delete options for this object mapper.
671+ */
672+ public void resetDefaultDeleteOptions() {
673+ this.defaultDeleteOptions = NO_OPTIONS;
674+ }
675+
676+ private static EnumMap<Option.Type, Option> toMap(Option[] options) {
677+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
678+ for (Option option : options) {
679+ result.put(option.type, option);
680+ }
681+ return result;
682+ }
683+
684+ private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
685+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
686+ for (Option option : options) {
687+ result.put(option.type, option);
688+ }
689+ return result;
690+ }
691+
692+ /**
693+ * An option for a mapper operation.
392694 * <p>
393- * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(primaryKey))}.
695+ * Options can be passed to individual operations:
696+ * <pre>
697+ * mapper.save(myObject, Option.ttl(3600));
698+ * </pre>
394699 *
395- * @param primaryKey the primary key of the entity to fetch, or more precisely
396- * the values for the columns of said primary key in the order of the primary key.
397- * @return a future on the fetched entity. The return future will yield
398- * {@code null} if said entity doesn't exist.
700+ * The mapper can also have defaults, that will apply to all operations that do not
701+ * override these particular option:
702+ * <pre>
703+ * mapper.setDefaultSaveOptions(Option.ttl(3600));
704+ * mapper.save(myObject);
705+ * </pre>
399706 *
400- * @throws IllegalArgumentException if the number of value provided differ from
401- * the number of columns composing the PRIMARY KEY of the mapped class, or if
402- * at least one of those values is {@code null}.
403- */
404- public ListenableFuture<T> getAsync(Object... primaryKey) {
405- return Futures.transform(session().executeAsync(getQuery(primaryKey)), mapOneFunction);
707+ * <p>
708+ * See the static methods in this class for available options.
709+ */
710+ public static abstract class Option {
711+
712+ enum Type {TTL, TIMESTAMP, CL, TRACING}
713+
714+ final Type type;
715+
716+ protected Option(Type type) {
717+ this.type = type;
718+ }
719+
720+ /**
721+ * Creates a new Option object to add time-to-live to a mapper operation. This is
722+ * only valid for save operations.
723+ * <p>
724+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
725+ *
726+ * @param ttl the TTL (in seconds).
727+ * @return the option.
728+ */
729+ public static Option ttl(int ttl) {
730+ return new Ttl(ttl);
731+ }
732+
733+ /**
734+ * Creates a new Option object to add a timestamp to a mapper operation. This is
735+ * only valid for save and delete operations.
736+ * <p>
737+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
738+ *
739+ * @param timestamp the timestamp (in microseconds).
740+ * @return the option.
741+ */
742+ public static Option timestamp(long timestamp) {
743+ return new Timestamp(timestamp);
744+ }
745+
746+ /**
747+ * Creates a new Option object to add a consistency level value to a mapper operation. This
748+ * is valid for save, delete and get operations.
749+ * <p>
750+ * Note that the consistency level can also be defined at the mapper level, as a parameter
751+ * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
752+ * for backward compatibility). This option, whether defined on a specific call or as the
753+ * default, will always take precedence over the annotation.
754+ *
755+ * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
756+ * @return the option.
757+ */
758+ public static Option consistencyLevel(ConsistencyLevel cl) {
759+ return new ConsistencyLevelOption(cl);
760+ }
761+
762+ /**
763+ * Creates a new Option object to enable query tracing for a mapper operation.
764+ *
765+ * @param enabled whether to enable tracing.
766+ * @return the option.
767+ */
768+ public static Option tracing(boolean enabled) {
769+ return new Tracing(enabled);
770+ }
771+
772+ abstract void appendTo(Insert.Options usings);
773+
774+ abstract void appendTo(Delete.Options usings);
775+
776+ abstract void addToPreparedStatement(BoundStatement bs, int i);
777+
778+ abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
779+
780+ abstract boolean isIncludedInQuery();
781+
782+ static class Ttl extends Option {
783+
784+ private int ttlValue;
785+
786+ Ttl(int value) {
787+ super(Type.TTL);
788+ this.ttlValue = value;
789+ }
790+
791+ void appendTo(Insert.Options usings) {
792+ usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
793+ }
794+ @Override
795+ void appendTo(Delete.Options usings) {
796+ throw new UnsupportedOperationException("shouldn't be called");
797+ }
798+ @Override
799+ void addToPreparedStatement(BoundStatement bs, int i) {
800+ bs.setInt(i, this.ttlValue);
801+ }
802+ @Override
803+ void checkValidFor(QueryType qt, MappingManager manager) {
804+ checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
805+ checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
806+ }
807+ @Override
808+ boolean isIncludedInQuery() {
809+ return true;
810+ }
811+ }
812+
813+ static class Timestamp extends Option {
814+
815+ private long tsValue;
816+
817+ Timestamp(long value) {
818+ super(Type.TIMESTAMP);
819+ this.tsValue = value;
820+ }
821+ @Override
822+ void appendTo(Insert.Options usings) {
823+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
824+ }
825+ @Override
826+ void appendTo(Delete.Options usings) {
827+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
828+ }
829+ @Override
830+ void checkValidFor(QueryType qt, MappingManager manager) {
831+ checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
832+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
833+ }
834+ @Override
835+ void addToPreparedStatement(BoundStatement bs, int i) {
836+ bs.setLong(i, this.tsValue);
837+ }
838+ @Override
839+ boolean isIncludedInQuery() {
840+ return true;
841+ }
842+ }
843+
844+ static class ConsistencyLevelOption extends Option {
845+
846+ private ConsistencyLevel cl;
847+
848+ ConsistencyLevelOption(ConsistencyLevel cl) {
849+ super(Type.CL);
850+ this.cl = cl;
851+ }
852+ @Override
853+ void appendTo(Insert.Options usings) {
854+ throw new UnsupportedOperationException("shouldn't be called");
855+ }
856+ @Override
857+ void appendTo(Delete.Options usings) {
858+ throw new UnsupportedOperationException("shouldn't be called");
859+ }
860+
861+ @Override
862+ void addToPreparedStatement(BoundStatement bs, int i) {
863+ bs.setConsistencyLevel(cl);
864+ }
865+ @Override
866+ void checkValidFor(QueryType qt, MappingManager manager) {
867+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
868+ "Consistency level option is only allowed in save, delete and get queries");
869+ }
870+
871+ @Override
872+ boolean isIncludedInQuery() {
873+ return false;
874+ }
875+ }
876+
877+ static class Tracing extends Option {
878+
879+ private boolean tracing;
880+
881+ Tracing(boolean tracing) {
882+ super(Type.TRACING);
883+ this.tracing = tracing;
884+ }
885+ @Override
886+ void appendTo(Insert.Options usings) {
887+ throw new UnsupportedOperationException("shouldn't be called");
888+ }
889+ @Override
890+ void appendTo(Delete.Options usings) {
891+ throw new UnsupportedOperationException("shouldn't be called");
892+ }
893+
894+ @Override
895+ void addToPreparedStatement(BoundStatement bs, int i) {
896+ if (this.tracing)
897+ bs.enableTracing();
898+ }
899+
900+ @Override
901+ void checkValidFor(QueryType qt, MappingManager manager) {
902+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
903+ "Tracing option is only allowed in save, delete and get queries");
904+ }
905+
906+ @Override
907+ boolean isIncludedInQuery() {
908+ return false;
909+ }
910+ }
911+ }
912+
913+ private static class MapperQueryKey {
914+ private final QueryType queryType;
915+ private final EnumSet<Option.Type> optionTypes;
916+
917+ MapperQueryKey(QueryType queryType, EnumMap<Option.Type, Option> options) {
918+ Preconditions.checkNotNull(queryType);
919+ Preconditions.checkNotNull(options);
920+ this.queryType = queryType;
921+ this.optionTypes = EnumSet.noneOf(Option.Type.class);
922+ for (Option opt : options.values()) {
923+ if (opt.isIncludedInQuery())
924+ this.optionTypes.add(opt.type);
925+ }
926+ }
927+
928+ @Override
929+ public boolean equals(Object other) {
930+ if (this == other)
931+ return true;
932+ if (other instanceof MapperQueryKey) {
933+ MapperQueryKey that = (MapperQueryKey)other;
934+ return this.queryType.equals(that.queryType)
935+ && this.optionTypes.equals(that.optionTypes);
936+ }
937+ return false;
938+ }
939+
940+ public int hashCode() {
941+ return Objects.hashCode(queryType, optionTypes);
942+ }
406943 }
407944 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +31 −9
@@ -24,15 +24,13 @@
2424 import com.datastax.driver.mapping.annotations.Accessor;
2525 import com.datastax.driver.mapping.annotations.Table;
2626
27-import com.datastax.driver.mapping.annotations.UDT;
28-
2927 /**
3028 * Mapping manager from which to obtain entity mappers.
3129 */
3230 public class MappingManager {
3331
3432 private final Session session;
35- final boolean supportsAliases;
33+ final boolean isCassandraV1;
3634
3735 private volatile Map<Class<?>, Mapper<?>> mappers = Collections.<Class<?>, Mapper<?>>emptyMap();
3836 private volatile Map<Class<?>, UDTMapper<?>> udtMappers = Collections.<Class<?>, UDTMapper<?>>emptyMap();
@@ -40,17 +38,41 @@
4038
4139 /**
4240 * Creates a new {@code MappingManager} using the provided {@code Session}.
41+ * <p>
42+ * Note that this constructor forces the initialization of the session (see
43+ * {@link #MappingManager(Session, ProtocolVersion)} if that is a problem for you).
4344 *
4445 * @param session the {@code Session} to use.
4546 */
4647 public MappingManager(Session session) {
47- this.session = session;
48+ this(session, getProtocolVersion(session));
49+ }
4850
49- ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
50- // The real condition should be Cassandra version >= 2.0, but mappers need this so that generated queries are compatible,
51- // and we don't know in advance the version of all future peers.
52- // At least if protocol >=2 we know there won't be any 1.2 nodes.
53- this.supportsAliases = (protocolVersion != ProtocolVersion.V1);
51+ private static ProtocolVersion getProtocolVersion(Session session) {
52+ session.init();
53+ return session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
54+ }
55+
56+ /**
57+ * Creates a new {@code MappingManager} using the provided {@code Session}.
58+ * <p>
59+ * This constructor is only provided for backward compatibility: before 2.1.7, {@code MappingManager} could be
60+ * built from an uninitialized session; since 2.1.7, the mapper needs to know the active protocol version to
61+ * adapt its internal requests, so {@link #MappingManager(Session)} will now initialize the session if needed.
62+ * If you rely on the session not being initialized, use this constructor and provide the version manually.
63+ *
64+ * @param session the {@code Session} to use.
65+ * @param protocolVersion the protocol version that will be used with this session.
66+ *
67+ * @since 2.1.7
68+ */
69+ public MappingManager(Session session, ProtocolVersion protocolVersion) {
70+ this.session = session;
71+ // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol.
72+ // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance
73+ // which nodes might join the cluster later.
74+ // At least if protocol >=2 we know there won't be any 1.2 nodes ever.
75+ this.isCassandraV1 = (protocolVersion == ProtocolVersion.V1);
5476 }
5577
5678 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +95 −80
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.util.ArrayList;
19+import java.util.Collection;
1920 import java.util.List;
2021
2122 import com.google.common.base.Objects;
@@ -29,7 +30,8 @@
2930
3031 class QueryType {
3132
32- private enum Kind { SAVE, GET, DEL, SLICE, REVERSED_SLICE };
33+ private enum Kind {SAVE, GET, DEL, SLICE, REVERSED_SLICE}
34+
3335 private final Kind kind;
3436
3537 // For slices
@@ -58,100 +60,112 @@
5860 return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
5961 }
6062
61- String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper) {
63+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Collection<Mapper.Option> options) {
6264 switch (kind) {
63- case SAVE:
64- {
65- Insert insert = table == null
66- ? insertInto(mapper.getKeyspace(), mapper.getTable())
67- : insertInto(table);
68- for (ColumnMapper<?> cm : mapper.allColumns())
69- if (cm.kind != ColumnMapper.Kind.COMPUTED)
70- insert.value(cm.getColumnName(), bindMarker());
71- return insert.toString();
65+ case SAVE: {
66+ Insert insert = table == null
67+ ? insertInto(mapper.getKeyspace(), mapper.getTable())
68+ : insertInto(table);
69+ for (ColumnMapper<?> cm : mapper.allColumns())
70+ if (cm.kind != ColumnMapper.Kind.COMPUTED)
71+ insert.value(cm.getColumnName(), bindMarker());
72+
73+ Insert.Options usings = insert.using();
74+ for (Mapper.Option opt : options) {
75+ opt.checkValidFor(QueryType.SAVE, manager);
76+ if (opt.isIncludedInQuery())
77+ opt.appendTo(usings);
7278 }
73- case GET:
74- {
75- Select.Selection selection = select();
76- for (ColumnMapper cm : mapper.allColumns()) {
77- Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
78- ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
79- : selection.column(cm.getColumnName());
80-
81- if (cm.getAlias() == null) {
82- selection = column;
83- } else {
84- selection = column.as(cm.getAlias());
85- }
86- }
87- Select select;
88- if (table == null) {
89- select = selection.from(mapper.getKeyspace(), mapper.getTable());
79+ return insert.toString();
80+ }
81+ case GET: {
82+ Select.Selection selection = select();
83+ for (ColumnMapper cm : mapper.allColumns()) {
84+ Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
85+ ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
86+ : selection.column(cm.getColumnName());
87+
88+ if (cm.getAlias() == null) {
89+ selection = column;
9090 } else {
91- select = selection.from(table);
91+ selection = column.as(cm.getAlias());
9292 }
93- Select.Where where = select.where();
94- for (int i = 0; i < mapper.primaryKeySize(); i++)
95- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
96- return select.toString();
9793 }
98- case DEL:
99- {
100- Delete delete = table == null
101- ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
102- : delete().all().from(table);
103- Delete.Where where = delete.where();
104- for (int i = 0; i < mapper.primaryKeySize(); i++)
105- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
106- return delete.toString();
94+ Select select;
95+ if (table == null) {
96+ select = selection.from(mapper.getKeyspace(), mapper.getTable());
97+ } else {
98+ select = selection.from(table);
10799 }
100+ Select.Where where = select.where();
101+ for (int i = 0; i < mapper.primaryKeySize(); i++)
102+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
103+
104+ for (Mapper.Option opt : options)
105+ opt.checkValidFor(QueryType.GET, manager);
106+ return select.toString();
107+ }
108+ case DEL: {
109+ Delete delete = table == null
110+ ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
111+ : delete().all().from(table);
112+ Delete.Where where = delete.where();
113+ for (int i = 0; i < mapper.primaryKeySize(); i++)
114+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
115+ Delete.Options usings = delete.using();
116+ for (Mapper.Option opt : options) {
117+ opt.checkValidFor(QueryType.DEL, manager);
118+ if (opt.isIncludedInQuery())
119+ opt.appendTo(usings);
120+ }
121+ return delete.toString();
122+ }
108123 case SLICE:
109- case REVERSED_SLICE:
110- {
111- Select select = table == null
112- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
113- : select().all().from(table);
114- Select.Where where = select.where();
115- for (int i = 0; i < mapper.partitionKeys.size(); i++)
116- where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
117-
118- if (startBoundSize > 0) {
119- if (startBoundSize == 1) {
120- String name = mapper.clusteringColumns.get(0).getColumnName();
121- where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
122- } else {
123- List<String> names = new ArrayList<String>(startBoundSize);
124- List<Object> values = new ArrayList<Object>(startBoundSize);
125- for (int i = 0; i < startBoundSize; i++) {
126- names.add(mapper.clusteringColumns.get(i).getColumnName());
127- values.add(bindMarker());
128- }
129- where.and(startInclusive ? gte(names, values) : gt(names, values));
124+ case REVERSED_SLICE: {
125+ Select select = table == null
126+ ? select().all().from(mapper.getKeyspace(), mapper.getTable())
127+ : select().all().from(table);
128+ Select.Where where = select.where();
129+ for (int i = 0; i < mapper.partitionKeys.size(); i++)
130+ where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
131+
132+ if (startBoundSize > 0) {
133+ if (startBoundSize == 1) {
134+ String name = mapper.clusteringColumns.get(0).getColumnName();
135+ where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
136+ } else {
137+ List<String> names = new ArrayList<String>(startBoundSize);
138+ List<Object> values = new ArrayList<Object>(startBoundSize);
139+ for (int i = 0; i < startBoundSize; i++) {
140+ names.add(mapper.clusteringColumns.get(i).getColumnName());
141+ values.add(bindMarker());
130142 }
143+ where.and(startInclusive ? gte(names, values) : gt(names, values));
131144 }
145+ }
132146
133- if (endBoundSize > 0) {
134- if (endBoundSize == 1) {
135- String name = mapper.clusteringColumns.get(0).getColumnName();
136- where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
137- } else {
138- List<String> names = new ArrayList<String>(endBoundSize);
139- List<Object> values = new ArrayList<Object>(endBoundSize);
140- for (int i = 0; i < endBoundSize; i++) {
141- names.add(mapper.clusteringColumns.get(i).getColumnName());
142- values.add(bindMarker());
143- }
144- where.and(endInclusive ? lte(names, values) : lt(names, values));
147+ if (endBoundSize > 0) {
148+ if (endBoundSize == 1) {
149+ String name = mapper.clusteringColumns.get(0).getColumnName();
150+ where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
151+ } else {
152+ List<String> names = new ArrayList<String>(endBoundSize);
153+ List<Object> values = new ArrayList<Object>(endBoundSize);
154+ for (int i = 0; i < endBoundSize; i++) {
155+ names.add(mapper.clusteringColumns.get(i).getColumnName());
156+ values.add(bindMarker());
145157 }
158+ where.and(endInclusive ? lte(names, values) : lt(names, values));
146159 }
160+ }
147161
148- select = select.limit(bindMarker());
162+ select = select.limit(bindMarker());
149163
150- if (kind == Kind.REVERSED_SLICE)
151- select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
164+ if (kind == Kind.REVERSED_SLICE)
165+ select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
152166
153- return select.toString();
154- }
167+ return select.toString();
168+ }
155169 }
156170 throw new AssertionError();
157171 }
@@ -175,4 +189,5 @@
175189 public int hashCode() {
176190 return Objects.hashCode(kind, startBoundSize, startInclusive, endBoundSize, endInclusive);
177191 }
192+
178193 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +9 −7
@@ -18,14 +18,16 @@
1818 import java.beans.IntrospectionException;
1919 import java.beans.PropertyDescriptor;
2020 import java.lang.reflect.Field;
21+import java.lang.reflect.Method;
2122 import java.lang.reflect.ParameterizedType;
2223 import java.lang.reflect.Type;
23-import java.lang.reflect.Method;
24-import java.util.*;
24+import java.util.HashMap;
25+import java.util.Map;
2526 import java.util.concurrent.atomic.AtomicInteger;
2627
27-import com.datastax.driver.core.*;
28-import com.datastax.driver.mapping.annotations.Computed;
28+import com.datastax.driver.core.ConsistencyLevel;
29+import com.datastax.driver.core.DataType;
30+import com.datastax.driver.core.UDTValue;
2931
3032 /**
3133 * An {@link EntityMapper} implementation that use reflection to read and write fields
@@ -110,7 +112,7 @@
110112 }
111113
112114 @SuppressWarnings("rawtypes")
113- @Override
115+ @Override
114116 public Object getValue(T entity) {
115117 Object value = super.getValue(entity);
116118 switch (enumType) {
@@ -148,14 +150,14 @@
148150 @Override
149151 public Object getValue(T entity) {
150152 @SuppressWarnings("unchecked")
151- U udtEntity = (U) super.getValue(entity);
153+ U udtEntity = (U)super.getValue(entity);
152154 return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
153155 }
154156
155157 @Override
156158 public void setValue(Object entity, Object value) {
157159 assert value instanceof UDTValue;
158- UDTValue udtValue = (UDTValue) value;
160+ UDTValue udtValue = (UDTValue)value;
159161 assert udtValue.getType().equals(udtMapper.getUserType());
160162
161163 super.setValue(entity, udtMapper.toEntity((udtValue)));
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +373 −0
@@ -0,0 +1,373 @@
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+ */
16+package com.datastax.driver.mapping;
17+
18+import java.util.Collection;
19+import java.util.concurrent.ExecutionException;
20+
21+import com.google.common.collect.Lists;
22+import org.testng.SkipException;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.assertj.core.api.Assertions.fail;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.exceptions.NoHostAvailableException;
31+import com.datastax.driver.core.exceptions.UnavailableException;
32+import com.datastax.driver.core.utils.CassandraVersion;
33+import com.datastax.driver.mapping.annotations.PartitionKey;
34+import com.datastax.driver.mapping.annotations.Table;
35+
36+import static com.datastax.driver.core.ConsistencyLevel.TWO;
37+import static com.datastax.driver.core.ProtocolVersion.V1;
38+import static com.datastax.driver.mapping.Mapper.Option;
39+
40+public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster {
41+
42+ ProtocolVersion protocolVersion;
43+ Mapper<User> mapper;
44+
45+ @Override
46+ protected Collection<String> getTableDefinitions() {
47+ return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)");
48+ }
49+
50+ @BeforeMethod(groups = "short")
51+ public void setup() {
52+ mapper = new MappingManager(session).mapper(User.class);
53+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
54+ }
55+
56+ @Test(groups = "short")
57+ @CassandraVersion(major = 2.0)
58+ void should_use_save_options() {
59+ Long tsValue = futureTimestamp();
60+ mapper.saveAsync(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
61+ assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
62+ Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
63+ assertThat(tsReturned).isEqualTo(tsValue);
64+ }
65+
66+ @Test(groups = "short")
67+ @CassandraVersion(major = 2.0)
68+ void should_use_delete_options() {
69+ User todelete = new User(45, "todelete");
70+ mapper.save(todelete);
71+ Option opt = Option.timestamp(35);
72+ BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(ConsistencyLevel.ALL));
73+ assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
74+ }
75+
76+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
77+ @CassandraVersion(major = 2.0)
78+ void should_use_get_options() {
79+ User todelete = new User(45, "toget");
80+ mapper.save(todelete);
81+
82+ Option opt = Option.tracing(true);
83+ BoundStatement bs = (BoundStatement)mapper.getQuery(45, opt);
84+ assertThat(bs.isTracing()).isTrue();
85+
86+ User us = mapper.mapAliased(session.execute(bs)).one();
87+ assertThat(us.getV()).isEqualTo("toget");
88+
89+ mapper.getQuery(45, Option.timestamp(1337));
90+ }
91+
92+ @Test(groups = "short")
93+ @CassandraVersion(major = 2.0)
94+ void should_use_options_only_once() {
95+ Long tsValue = futureTimestamp();
96+ mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
97+ mapper.save(new User(44, "test"));
98+ Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
99+ // Assuming we cannot go back in time (yet) and execute the write at ts=1
100+ assertThat(tsReturned).isNotEqualTo(tsValue);
101+ }
102+
103+ @Test(groups = "short")
104+ @CassandraVersion(major = 2.0)
105+ void should_use_default_options() {
106+ mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
107+ BoundStatement bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"));
108+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
109+
110+ mapper.resetDefaultSaveOptions();
111+ bs = (BoundStatement)mapper.saveQuery(new User(47, "rjhrgce"));
112+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
113+
114+ mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
115+ bs = (BoundStatement)mapper.deleteQuery(47);
116+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
117+ assertThat(bs.isTracing()).isTrue();
118+
119+ mapper.resetDefaultDeleteOptions();
120+ bs = (BoundStatement)mapper.deleteQuery(47);
121+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
122+ assertThat(bs.isTracing()).isFalse();
123+
124+ bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
125+ assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
126+
127+ mapper.setDefaultGetOptions(Option.tracing(true));
128+ bs = (BoundStatement)mapper.getQuery(46);
129+ assertThat(bs.isTracing()).isTrue();
130+
131+ mapper.resetDefaultGetOptions();
132+ bs = (BoundStatement)mapper.getQuery(46);
133+ assertThat(bs.isTracing()).isFalse();
134+ }
135+
136+ @Test(groups = "short")
137+ @CassandraVersion(major = 2.0)
138+ void should_use_explicit_options_over_default_options() {
139+ long defaultTimestamp = futureTimestamp();
140+ long explicitTimestamp = futureTimestamp();
141+
142+ mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
143+
144+ mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
145+ Long savedTimestamp = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
146+ assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
147+ }
148+
149+ /** Cover all versions of save() to check that methods that call each other properly propagate the options */
150+ @Test(groups = "short")
151+ @CassandraVersion(major = 2.0)
152+ void should_use_save_options_for_all_variants() throws ExecutionException, InterruptedException {
153+ Long timestamp = futureTimestamp();
154+ User user = new User(42, "helloworld");
155+
156+ mapper.save(user, Option.timestamp(timestamp));
157+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
158+ mapper.delete(user.getKey());
159+
160+ mapper.saveAsync(user, Option.timestamp(timestamp)).get();
161+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
162+ mapper.delete(user.getKey());
163+
164+ session.execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
165+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
166+ mapper.delete(user.getKey());
167+
168+ // Set as default and try optionless methods
169+ mapper.setDefaultSaveOptions(Option.timestamp(timestamp));
170+
171+ mapper.save(user);
172+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
173+ mapper.delete(user.getKey());
174+
175+ mapper.saveAsync(user).get();
176+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
177+ mapper.delete(user.getKey());
178+
179+ session.execute(mapper.saveQuery(user));
180+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
181+ mapper.delete(user.getKey());
182+ }
183+
184+ private Long getWriteTime(int key) {
185+ Row row = session.execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
186+ return row.getLong(0);
187+ }
188+
189+ @Test(groups = "short")
190+ @CassandraVersion(major = 2.0)
191+ void should_use_get_options_for_all_variants() throws InterruptedException {
192+ try {
193+ mapper.get(42, Option.consistencyLevel(TWO));
194+ fail("Expected a NoHostAvailableException");
195+ } catch (NoHostAvailableException e) {
196+ assertFirstNodeUnavailable(e);
197+ }
198+
199+ try {
200+ mapper.getAsync(42, Option.consistencyLevel(TWO)).get();
201+ fail("Expected an ExecutionException");
202+ } catch (ExecutionException e) {
203+ assertFirstNodeUnavailable(e);
204+ }
205+
206+ Statement statement = mapper.getQuery(42, Option.consistencyLevel(TWO));
207+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
208+
209+ // Set as default and try optionless methods
210+ mapper.setDefaultGetOptions(Option.consistencyLevel(TWO));
211+
212+ try {
213+ mapper.get(42);
214+ fail("Expected a NoHostAvailableException");
215+ } catch (NoHostAvailableException e) {
216+ assertFirstNodeUnavailable(e);
217+ }
218+
219+ try {
220+ mapper.getAsync(42).get();
221+ fail("Expected an ExecutionException");
222+ } catch (ExecutionException e) {
223+ assertFirstNodeUnavailable(e);
224+ }
225+
226+ statement = mapper.getQuery(42);
227+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
228+ }
229+
230+ @Test(groups = "short")
231+ @CassandraVersion(major = 2.0)
232+ void should_use_delete_options_for_all_variants() throws InterruptedException {
233+ User user = new User(42, "helloworld");
234+
235+ try {
236+ mapper.delete(user, Option.consistencyLevel(TWO));
237+ fail("Expected a NoHostAvailableException");
238+ } catch (NoHostAvailableException e) {
239+ assertFirstNodeUnavailable(e);
240+ }
241+
242+ try {
243+ mapper.deleteAsync(user, Option.consistencyLevel(TWO)).get();
244+ fail("Expected an ExecutionException");
245+ } catch (ExecutionException e) {
246+ assertFirstNodeUnavailable(e);
247+ }
248+
249+ Statement statement = mapper.deleteQuery(user, Option.consistencyLevel(TWO));
250+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
251+
252+ try {
253+ mapper.delete(user.getKey(), Option.consistencyLevel(TWO));
254+ fail("Expected a NoHostAvailableException");
255+ } catch (NoHostAvailableException e) {
256+ assertFirstNodeUnavailable(e);
257+ }
258+
259+ try {
260+ mapper.deleteAsync(user.getKey(), Option.consistencyLevel(TWO)).get();
261+ fail("Expected an ExecutionException");
262+ } catch (ExecutionException e) {
263+ assertFirstNodeUnavailable(e);
264+ }
265+
266+ statement = mapper.deleteQuery(user.getKey(), Option.consistencyLevel(TWO));
267+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
268+
269+ // Set as default and try optionless methods
270+ mapper.setDefaultDeleteOptions(Option.consistencyLevel(TWO));
271+
272+ try {
273+ mapper.delete(user);
274+ fail("Expected a NoHostAvailableException");
275+ } catch (NoHostAvailableException e) {
276+ assertFirstNodeUnavailable(e);
277+ }
278+
279+ try {
280+ mapper.deleteAsync(user).get();
281+ fail("Expected an ExecutionException");
282+ } catch (ExecutionException e) {
283+ assertFirstNodeUnavailable(e);
284+ }
285+
286+ statement = mapper.deleteQuery(user);
287+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
288+
289+ try {
290+ mapper.delete(user.getKey());
291+ fail("Expected a NoHostAvailableException");
292+ } catch (NoHostAvailableException e) {
293+ assertFirstNodeUnavailable(e);
294+ }
295+
296+ try {
297+ mapper.deleteAsync(user.getKey()).get();
298+ fail("Expected an ExecutionException");
299+ } catch (ExecutionException e) {
300+ assertFirstNodeUnavailable(e);
301+ }
302+
303+ statement = mapper.deleteQuery(user.getKey());
304+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
305+ }
306+
307+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
308+ void should_fail_if_option_does_not_apply_to_query() {
309+ mapper.get(42, Option.ttl(1));
310+ }
311+
312+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
313+ void should_fail_when_using_ttl_with_protocol_v1() {
314+ if (protocolVersion.compareTo(V1) > 0)
315+ throw new SkipException("Skipped when protocol version > V1");
316+
317+ mapper.saveQuery(new User(42, "helloworld"), Option.ttl(15));
318+ }
319+
320+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
321+ void should_fail_when_using_timestamp_with_protocol_v1() {
322+ if (protocolVersion.compareTo(V1) > 0)
323+ throw new SkipException("Skipped when protocol version > V1");
324+
325+ mapper.saveQuery(new User(42, "helloworld"), Option.timestamp(15));
326+ }
327+
328+ private static void assertFirstNodeUnavailable(NoHostAvailableException e) {
329+ Throwable node1Error = e.getErrors().values().iterator().next();
330+ assertThat(node1Error).isInstanceOf(UnavailableException.class);
331+ }
332+
333+ private static void assertFirstNodeUnavailable(ExecutionException e) {
334+ Throwable cause = e.getCause();
335+ assertThat(cause).isInstanceOf(NoHostAvailableException.class);
336+ assertFirstNodeUnavailable((NoHostAvailableException)cause);
337+ }
338+
339+ private static long futureTimestamp() {
340+ return (System.currentTimeMillis() + 1000) * 1000;
341+ }
342+
343+ @Table(name = "user", writeConsistency = "ONE")
344+ public static class User {
345+ @PartitionKey
346+ private int key;
347+ private String v;
348+
349+ public User() {
350+ }
351+
352+ public User(int k, String val) {
353+ this.key = k;
354+ this.v = val;
355+ }
356+
357+ public int getKey() {
358+ return this.key;
359+ }
360+
361+ public void setKey(int pk) {
362+ this.key = pk;
363+ }
364+
365+ public String getV() {
366+ return this.v;
367+ }
368+
369+ public void setV(String val) {
370+ this.v = val;
371+ }
372+ }
373+}
modified upgrade_guide/README.md +26 −0
@@ -5,6 +5,9 @@
55
66 ### 2.1.7
77
8+This version brings a few changes in the driver's behavior; none of them break
9+binary compatibility.
10+
811 1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
912 exception received from a request. The new behaviour will cause the driver to
1013 process a Retry on a different node at most once, otherwise an exception will
@@ -25,6 +28,29 @@
2528 use multiple connections. See [this page](../features/pooling) for more
2629 information.
2730
31+3. `MappingManager(Session)` will now force the initialization of the `Session`
32+ if needed. This is a change from 2.1.6, where if you gave it an uninitialized
33+ session (created with `Cluster#newSession()` instead of `Cluster#connect()`),
34+ it would only get initialized on the first request.
35+
36+ If this is a problem for you, `MappingManager(Session, ProtocolVersion)`
37+ preserves the previous behavior (see the API docs for more details).
38+
39+Merged from 2.0.11:
40+
41+4. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
42+ exception received from a request. The new behaviour will cause the driver to
43+ process a Retry on a different node at most once, otherwise an exception will
44+ be thrown. This change makes sense in the case where the node tried initially
45+ for the request happens to be isolated from the rest of the cluster (e.g.
46+ because of a network partition) but can still answer to the client normally.
47+ In this case, trying another node has a chance of success.
48+ The previous behaviour was to always throw an exception.
49+5. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
50+ or `raw()` is used to build a value to be inserted in the database.
51+ If you know that the CQL functions or expressions are safe, use
52+ `setIdempotent(true)` on the statement.
53+
2854
2955 ### 2.1.6
3056