Elffuss BraidHub

kikocis/java-driver public

Merge pull request #357 from datastax/java473

JAVA-473 : Strategies for saving null fields in mapped objects
Changesetbbf28cf9e1159ec1c26e2f5b8d82ac5d699595e1d3d778d49678ed28d1116bd8
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-07-01 15:26 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-07-01 15:26 +02:00
Parents835cbb4c43e6, 21d094a922a5

Browse the files at this changeset

13 files changed

modified changelog/README.md +3 −0
@@ -19,6 +19,9 @@
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)
24+- [improvement] Add mapper option to configure whether to save null fields (JAVA-473)
2225
2326 Merged from 2.0 branch:
2427
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 +731 −116
@@ -15,21 +15,29 @@
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;
35+import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
3036 import com.datastax.driver.mapping.annotations.Accessor;
3137 import com.datastax.driver.mapping.annotations.Computed;
3238
39+import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
40+
3341 /**
3442 * An object handling the mapping of a particular class.
3543 * <p>
@@ -47,9 +55,15 @@
4755 final TableMetadata tableMetadata;
4856
4957 // Cache prepared statements for each type of query we use.
50- private volatile Map<QueryType, PreparedStatement> preparedQueries = Collections.<QueryType, PreparedStatement>emptyMap();
58+ private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
59+
60+ private static final Function<Object, Void> NOOP = Functions.constant(null);
61+
62+ private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
63+ private volatile EnumMap<Option.Type, Option> defaultGetOptions;
64+ private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
5165
52- private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
66+ private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
5367
5468 final Function<ResultSet, T> mapOneFunction;
5569 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
@@ -79,23 +93,30 @@
7993 return Mapper.this.map(rs);
8094 }
8195 };
96+
97+ this.defaultSaveOptions = NO_OPTIONS;
98+ this.defaultGetOptions = NO_OPTIONS;
99+ this.defaultDeleteOptions = NO_OPTIONS;
82100 }
83101
84102 Session session() {
85103 return manager.getSession();
86104 }
87105
88- PreparedStatement getPreparedQuery(QueryType type) {
89- PreparedStatement stmt = preparedQueries.get(type);
106+ PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
107+
108+ MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
109+
110+ PreparedStatement stmt = preparedQueries.get(pqk);
90111 if (stmt == null) {
91112 synchronized (preparedQueries) {
92- stmt = preparedQueries.get(type);
113+ stmt = preparedQueries.get(pqk);
93114 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);
115+ String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
116+ logger.debug("Preparing query {}", queryString);
117+ stmt = session().prepare(queryString);
118+ Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
119+ newQueries.put(pqk, stmt);
99120 preparedQueries = newQueries;
100121 }
101122 }
@@ -103,6 +124,10 @@
103124 return stmt;
104125 }
105126
127+ PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
128+ return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
129+ }
130+
106131 /**
107132 * The {@code TableMetadata} for this mapper.
108133 *
@@ -134,22 +159,68 @@
134159 * @return a query that saves {@code entity} (based on it's defined mapping).
135160 */
136161 public Statement saveQuery(T entity) {
137- PreparedStatement ps = getPreparedQuery(QueryType.SAVE);
162+ return saveQuery(entity, this.defaultSaveOptions);
163+ }
164+
165+ /**
166+ * Creates a query that can be used to save the provided entity.
167+ * <p>
168+ * This method is useful if you want to setup a number of options (tracing,
169+ * conistency level, ...) of the returned statement before executing it manually
170+ * or need access to the {@code ResultSet} object after execution (to get the
171+ * trace, the execution info, ...), but in other cases, calling {@link #save}
172+ * or {@link #saveAsync} is shorter.
173+ * This method allows you to provide a suite of {@link Option} to include in
174+ * the SAVE query. Options currently supported for SAVE are :
175+ * <ul>
176+ * <li>Timestamp</li>
177+ * <li>Time-to-live (ttl)</li>
178+ * <li>Consistency level</li>
179+ * <li>Tracing</li>
180+ * </ul>
181+ *
182+ * @param entity the entity to save.
183+ * @return a query that saves {@code entity} (based on it's defined mapping).
184+ */
185+ public Statement saveQuery(T entity, Option... options) {
186+ return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
187+ }
188+
189+ private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
190+ Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
191+ boolean saveNullFields = shouldSaveNullFields(options);
138192
139- BoundStatement bs = ps.bind();
140- int i = 0;
141193 for (ColumnMapper<T> cm : mapper.allColumns()) {
142- if (cm.kind != ColumnMapper.Kind.COMPUTED) {
143- Object value = cm.getValue(entity);
144- bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
194+ Object value = cm.getValue(entity);
195+ if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) {
196+ values.put(cm, value);
145197 }
146198 }
147199
200+ BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
201+ int i = 0;
202+ for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
203+ DataType type = entry.getKey().getDataType();
204+ Object value = entry.getValue();
205+ bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
206+ }
207+
148208 if (mapper.writeConsistency != null)
149209 bs.setConsistencyLevel(mapper.writeConsistency);
210+
211+ for (Option opt : options.values()) {
212+ opt.checkValidFor(QueryType.SAVE, manager);
213+ opt.addToPreparedStatement(bs, i++);
214+ }
215+
150216 return bs;
151217 }
152218
219+ private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
220+ SaveNullFields option = (SaveNullFields)options.get(SAVE_NULL_FIELDS);
221+ return option == null || option.saveNullFields;
222+ }
223+
153224 /**
154225 * Save an entity mapped by this mapper.
155226 * <p>
@@ -162,7 +233,25 @@
162233 }
163234
164235 /**
165- * Save an entity mapped by this mapper asynchonously.
236+ * Save an entity mapped by this mapper and using special options for save.
237+ * This method allows you to provide a suite of {@link Option} to include in
238+ * the SAVE query. Options currently supported for SAVE are :
239+ * <ul>
240+ * <li>Timestamp</li>
241+ * <li>Time-to-live (ttl)</li>
242+ * <li>Consistency level</li>
243+ * <li>Tracing</li>
244+ * </ul>
245+ *
246+ * @param entity the entity to save.
247+ * @param options the options object specified defining special options when saving.
248+ */
249+ public void save(T entity, Option... options) {
250+ session().execute(saveQuery(entity, options));
251+ }
252+
253+ /**
254+ * Save an entity mapped by this mapper asynchronously.
166255 * <p>
167256 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
168257 *
@@ -173,6 +262,160 @@
173262 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
174263 }
175264
265+ /**
266+ * Save an entity mapped by this mapper asynchronously using special options for save.
267+ * <p>
268+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
269+ *
270+ * @param entity the entity to save.
271+ * @param options the options object specified defining special options when saving.
272+ * @return a future on the completion of the save operation.
273+ */
274+ public ListenableFuture<Void> saveAsync(T entity, Option... options) {
275+ return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
276+ }
277+
278+ /**
279+ * Creates a query to fetch entity given its PRIMARY KEY.
280+ * <p>
281+ * The values provided must correspond to the columns composing the PRIMARY
282+ * KEY (in the order of said primary key).
283+ * <p>
284+ * This method is useful if you want to setup a number of options (tracing,
285+ * conistency level, ...) of the returned statement before executing it manually,
286+ * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
287+ * <p>
288+ * This method allows you to provide a suite of {@link Option} to include in
289+ * the GET query. Options currently supported for GET are :
290+ * <ul>
291+ * <li>Consistency level</li>
292+ * <li>Tracing</li>
293+ * </ul>
294+ *
295+ * @param objects the primary key of the entity to fetch, or more precisely
296+ * the values for the columns of said primary key in the order of the primary key.
297+ * Can be followed by {@link Option} to include in the DELETE query.
298+ * @return a query that fetch the entity of PRIMARY KEY {@code objects}.
299+ * @throws IllegalArgumentException if the number of value provided differ from
300+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
301+ * at least one of those values is {@code null}.
302+ */
303+ public Statement getQuery(Object... objects) {
304+ // Order and duplicates matter for primary keys
305+ List<Object> pks = new ArrayList<Object>();
306+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
307+
308+ for (Object o : objects) {
309+ if (o instanceof Option) {
310+ Option option = (Option)o;
311+ options.put(option.type, option);
312+ } else {
313+ pks.add(o);
314+ }
315+ }
316+ return getQuery(pks, options);
317+ }
318+
319+ private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
320+
321+ if (primaryKeys.size() != mapper.primaryKeySize())
322+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
323+
324+ BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
325+ int i = 0;
326+ for (Object value : primaryKeys) {
327+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
328+ if (value == null) {
329+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
330+ }
331+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
332+ }
333+
334+ if (mapper.readConsistency != null)
335+ bs.setConsistencyLevel(mapper.readConsistency);
336+
337+ for (Option opt : options.values()) {
338+ opt.checkValidFor(QueryType.GET, manager);
339+ opt.addToPreparedStatement(bs, i);
340+ if (opt.isIncludedInQuery())
341+ i++;
342+ }
343+
344+ return bs;
345+ }
346+
347+ /**
348+ * Fetch an entity based on its primary key.
349+ * <p>
350+ * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
351+ *
352+ * @param objects the primary key of the entity to fetch, or more precisely
353+ * the values for the columns of said primary key in the order of the primary key.
354+ * Can be followed by {@link Option} to include in the DELETE query.
355+ * @return the entity fetched or {@code null} if it doesn't exist.
356+ * @throws IllegalArgumentException if the number of value provided differ from
357+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
358+ * at least one of those values is {@code null}.
359+ */
360+ public T get(Object... objects) {
361+ return mapAliased(session().execute(getQuery(objects))).one();
362+ }
363+
364+ /**
365+ * Fetch an entity based on its primary key asynchronously.
366+ * <p>
367+ * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
368+ *
369+ * @param objects the primary key of the entity to fetch, or more precisely
370+ * the values for the columns of said primary key in the order of the primary key.
371+ * Can be followed by {@link Option} to include in the DELETE query.
372+ * @return a future on the fetched entity. The return future will yield
373+ * {@code null} if said entity doesn't exist.
374+ * @throws IllegalArgumentException if the number of value provided differ from
375+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
376+ * at least one of those values is {@code null}.
377+ */
378+ public ListenableFuture<T> getAsync(Object... objects) {
379+ return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
380+ }
381+
382+ /**
383+ * Creates a query that can be used to delete the provided entity.
384+ * <p>
385+ * This method is a shortcut that extract the PRIMARY KEY from the
386+ * provided entity and call {@link #deleteQuery(Object...)} with it.
387+ * This method allows you to provide a suite of {@link Option} to include in
388+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
389+ * is supported for DELETE queries.
390+ * <p>
391+ * This method is useful if you want to setup a number of options (tracing,
392+ * conistency level, ...) of the returned statement before executing it manually
393+ * or need access to the {@code ResultSet} object after execution (to get the
394+ * trace, the execution info, ...), but in other cases, calling {@link #delete}
395+ * or {@link #deleteAsync} is shorter.
396+ * <p>
397+ * This method allows you to provide a suite of {@link Option} to include in
398+ * the DELETE query. Options currently supported for DELETE are :
399+ * <ul>
400+ * <li>Timestamp</li>
401+ * <li>Consistency level</li>
402+ * <li>Tracing</li>
403+ * </ul>
404+ *
405+ * @param entity the entity to delete.
406+ * @param options the options to add to the DELETE query.
407+ * @return a query that delete {@code entity} (based on it's defined mapping) with
408+ * provided USING options.
409+ */
410+ public Statement deleteQuery(T entity, Option... options) {
411+ List<Object> pks = new ArrayList<Object>();
412+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
413+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
414+ }
415+
416+ return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
417+ }
418+
176419 /**
177420 * Creates a query that can be used to delete the provided entity.
178421 * <p>
@@ -189,50 +432,87 @@
189432 * @return a query that delete {@code entity} (based on it's defined mapping).
190433 */
191434 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);
435+ List<Object> pks = new ArrayList<Object>();
436+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
437+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
438+ }
195439
196- return deleteQuery(pks);
440+ return deleteQuery(pks, defaultDeleteOptions);
197441 }
198442
199443 /**
200444 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
201445 * <p>
202446 * The values provided must correspond to the columns composing the PRIMARY
203- * KEY (in the order of said primary key).
447+ * KEY (in the order of said primary key). The values can also contain, after
448+ * specifying the primary keys columns, a suite of {@link Option} to include in
449+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
450+ * is supported for DELETE queries.
204451 * <p>
205452 * This method is useful if you want to setup a number of options (tracing,
206453 * conistency level, ...) of the returned statement before executing it manually
207454 * or need access to the {@code ResultSet} object after execution (to get the
208455 * trace, the execution info, ...), but in other cases, calling {@link #delete}
209456 * or {@link #deleteAsync} is shorter.
457+ * This method allows you to provide a suite of {@link Option} to include in
458+ * the DELETE query. Options currently supported for DELETE are :
459+ * <ul>
460+ * <li>Timestamp</li>
461+ * <li>Consistency level</li>
462+ * <li>Tracing</li>
463+ * </ul>
210464 *
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.
465+ * @param objects the primary key of the entity to delete, or more precisely
466+ * the values for the columns of said primary key in the order of the primary key.
467+ * Can be followed by {@link Option} to include in the DELETE
468+ * query.
213469 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
214- *
215470 * @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}.
471+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
472+ * at least one of those values is {@code null}.
218473 */
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));
474+ public Statement deleteQuery(Object... objects) {
475+ // Order and duplicates matter for primary keys
476+ List<Object> pks = new ArrayList<Object>();
477+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
478+
479+ for (Object o : objects) {
480+ if (o instanceof Option) {
481+ Option option = (Option)o;
482+ options.put(option.type, option);
483+ } else {
484+ pks.add(o);
485+ }
486+ }
487+ return deleteQuery(pks, options);
488+ }
222489
223- PreparedStatement ps = getPreparedQuery(QueryType.DEL);
490+ private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
491+ if (primaryKey.size() != mapper.primaryKeySize())
492+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
224493
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- }
494+ BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
233495
234496 if (mapper.writeConsistency != null)
235497 bs.setConsistencyLevel(mapper.writeConsistency);
498+
499+ int i = 0;
500+ for (Option opt : options.values()) {
501+ opt.checkValidFor(QueryType.DEL, manager);
502+ opt.addToPreparedStatement(bs, i);
503+ if (opt.isIncludedInQuery())
504+ i++;
505+ }
506+
507+ int columnNumber = 0;
508+ for (Object value : primaryKey) {
509+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
510+ if (value == null) {
511+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
512+ }
513+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
514+ columnNumber++;
515+ }
236516 return bs;
237517 }
238518
@@ -247,6 +527,18 @@
247527 session().execute(deleteQuery(entity));
248528 }
249529
530+ /**
531+ * Deletes an entity mapped by this mapper using provided options.
532+ * <p>
533+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
534+ *
535+ * @param entity the entity to delete.
536+ * @param options the options to add to the DELETE query.
537+ */
538+ public void delete(T entity, Option... options) {
539+ session().execute(deleteQuery(entity, options));
540+ }
541+
250542 /**
251543 * Deletes an entity mapped by this mapper asynchronously.
252544 * <p>
@@ -260,36 +552,50 @@
260552 }
261553
262554 /**
263- * Deletes an entity based on its primary key.
555+ * Deletes an entity mapped by this mapper asynchronously using provided options.
264556 * <p>
265- * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(primaryKey))}.
557+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
266558 *
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.
559+ * @param entity the entity to delete.
560+ * @param options the options to add to the DELETE query.
561+ * @return a future on the completion of the deletion.
562+ */
563+ public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
564+ return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
565+ }
566+
567+ /**
568+ * Deletes an entity based on its primary key.
569+ * <p>
570+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
269571 *
572+ * @param objects the primary key of the entity to delete, or more precisely
573+ * the values for the columns of said primary key in the order
574+ * of the primary key.Can be followed by {@link Option} to include
575+ * in the DELETE query.
270576 * @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}.
577+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
578+ * at least one of those values is {@code null}.
273579 */
274- public void delete(Object... primaryKey) {
275- session().execute(deleteQuery(primaryKey));
580+ public void delete(Object... objects) {
581+ session().execute(deleteQuery(objects));
276582 }
277583
278584 /**
279585 * Deletes an entity based on its primary key asynchronously.
280586 * <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.
587+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
286588 *
589+ * @param objects the primary key of the entity to delete, or more precisely
590+ * the values for the columns of said primary key in the order
591+ * of the primary key. Can be followed by {@link Option} to include
592+ * in the DELETE query.
287593 * @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}.
594+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
595+ * at least one of those values is {@code null}.
290596 */
291- public ListenableFuture<Void> deleteAsync(Object... primaryKey) {
292- return Futures.transform(session().executeAsync(deleteQuery(primaryKey)), NOOP);
597+ public ListenableFuture<Void> deleteAsync(Object... objects) {
598+ return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
293599 }
294600
295601 /**
@@ -327,81 +633,390 @@
327633 * @see #map(ResultSet)
328634 */
329635 public Result<T> mapAliased(ResultSet resultSet) {
330- return (manager.supportsAliases)
331- ? new Result<T>(resultSet, mapper, protocolVersion, true)
332- : map(resultSet);
636+ return (manager.isCassandraV1)
637+ ? map(resultSet) // no aliases
638+ : new Result<T>(resultSet, mapper, protocolVersion, true);
333639 }
334640
335641 /**
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.
344- *
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}.
642+ * Set the default save {@link Option} for this object mapper, that will be used
643+ * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
644+ * to check available save options.
348645 *
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}.
646+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
647+ */
648+ public void setDefaultSaveOptions(Option... options) {
649+ this.defaultSaveOptions = toMap(options);
650+ }
651+
652+ /**
653+ * Reset the default save options for this object mapper.
352654 */
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));
655+ public void resetDefaultSaveOptions() {
656+ this.defaultSaveOptions = NO_OPTIONS;
657+ }
356658
357- PreparedStatement ps = getPreparedQuery(QueryType.GET);
659+ /**
660+ * Set the default get {@link Option} for this object mapper, that will be used
661+ * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
662+ * get options.
663+ *
664+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
665+ */
666+ public void setDefaultGetOptions(Option... options) {
667+ this.defaultGetOptions = toMap(options);
358668
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- }
669+ }
367670
368- if (mapper.readConsistency != null)
369- bs.setConsistencyLevel(mapper.readConsistency);
370- return bs;
671+ /**
672+ * Reset the default save options for this object mapper.
673+ */
674+ public void resetDefaultGetOptions() {
675+ this.defaultGetOptions = NO_OPTIONS;
371676 }
372677
373678 /**
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()}.
679+ * Set the default delete {@link Option} for this object mapper, that will be used
680+ * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
681+ * to check available delete options.
377682 *
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.
381- *
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}.
683+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
385684 */
386- public T get(Object... primaryKey) {
387- return mapAliased(session().execute(getQuery(primaryKey))).one();
685+ public void setDefaultDeleteOptions(Option... options) {
686+ this.defaultDeleteOptions = toMap(options);
388687 }
389688
390689 /**
391- * Fetch an entity based on its primary key asynchronously.
690+ * Reset the default delete options for this object mapper.
691+ */
692+ public void resetDefaultDeleteOptions() {
693+ this.defaultDeleteOptions = NO_OPTIONS;
694+ }
695+
696+ private static EnumMap<Option.Type, Option> toMap(Option[] options) {
697+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
698+ for (Option option : options) {
699+ result.put(option.type, option);
700+ }
701+ return result;
702+ }
703+
704+ private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
705+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
706+ for (Option option : options) {
707+ result.put(option.type, option);
708+ }
709+ return result;
710+ }
711+
712+ /**
713+ * An option for a mapper operation.
392714 * <p>
393- * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(primaryKey))}.
715+ * Options can be passed to individual operations:
716+ * <pre>
717+ * mapper.save(myObject, Option.ttl(3600));
718+ * </pre>
394719 *
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.
720+ * The mapper can also have defaults, that will apply to all operations that do not
721+ * override these particular option:
722+ * <pre>
723+ * mapper.setDefaultSaveOptions(Option.ttl(3600));
724+ * mapper.save(myObject);
725+ * </pre>
399726 *
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);
727+ * <p>
728+ * See the static methods in this class for available options.
729+ */
730+ public static abstract class Option {
731+
732+ enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
733+
734+ final Type type;
735+
736+ protected Option(Type type) {
737+ this.type = type;
738+ }
739+
740+ /**
741+ * Creates a new Option object to add time-to-live to a mapper operation. This is
742+ * only valid for save operations.
743+ * <p>
744+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
745+ *
746+ * @param ttl the TTL (in seconds).
747+ * @return the option.
748+ */
749+ public static Option ttl(int ttl) {
750+ return new Ttl(ttl);
751+ }
752+
753+ /**
754+ * Creates a new Option object to add a timestamp to a mapper operation. This is
755+ * only valid for save and delete operations.
756+ * <p>
757+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
758+ *
759+ * @param timestamp the timestamp (in microseconds).
760+ * @return the option.
761+ */
762+ public static Option timestamp(long timestamp) {
763+ return new Timestamp(timestamp);
764+ }
765+
766+ /**
767+ * Creates a new Option object to add a consistency level value to a mapper operation. This
768+ * is valid for save, delete and get operations.
769+ * <p>
770+ * Note that the consistency level can also be defined at the mapper level, as a parameter
771+ * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
772+ * for backward compatibility). This option, whether defined on a specific call or as the
773+ * default, will always take precedence over the annotation.
774+ *
775+ * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
776+ * @return the option.
777+ */
778+ public static Option consistencyLevel(ConsistencyLevel cl) {
779+ return new ConsistencyLevelOption(cl);
780+ }
781+
782+ /**
783+ * Creates a new Option object to enable query tracing for a mapper operation. This
784+ * is valid for save, delete and get operations.
785+ *
786+ * @param enabled whether to enable tracing.
787+ * @return the option.
788+ */
789+ public static Option tracing(boolean enabled) {
790+ return new Tracing(enabled);
791+ }
792+
793+ /**
794+ * Creates a new Option object to specify whether null entity fields should be included in
795+ * insert queries. This option is valid only for save operations.
796+ *
797+ * If this option is not specified, it defaults to {@code true} (null fields are saved).
798+ *
799+ * @param enabled whether to include null fields in queries.
800+ * @return the option.
801+ */
802+ public static Option saveNullFields(boolean enabled){
803+ return new SaveNullFields(enabled);
804+ }
805+
806+ public Type getType(){
807+ return this.type;
808+ }
809+
810+ abstract void appendTo(Insert.Options usings);
811+
812+ abstract void appendTo(Delete.Options usings);
813+
814+ abstract void addToPreparedStatement(BoundStatement bs, int i);
815+
816+ abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
817+
818+ abstract boolean isIncludedInQuery();
819+
820+ static class Ttl extends Option {
821+
822+ private int ttlValue;
823+
824+ Ttl(int value) {
825+ super(Type.TTL);
826+ this.ttlValue = value;
827+ }
828+
829+ void appendTo(Insert.Options usings) {
830+ usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
831+ }
832+ @Override
833+ void appendTo(Delete.Options usings) {
834+ throw new UnsupportedOperationException("shouldn't be called");
835+ }
836+ @Override
837+ void addToPreparedStatement(BoundStatement bs, int i) {
838+ bs.setInt(i, this.ttlValue);
839+ }
840+ @Override
841+ void checkValidFor(QueryType qt, MappingManager manager) {
842+ checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
843+ checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
844+ }
845+ @Override
846+ boolean isIncludedInQuery() {
847+ return true;
848+ }
849+ }
850+
851+ static class Timestamp extends Option {
852+
853+ private long tsValue;
854+
855+ Timestamp(long value) {
856+ super(Type.TIMESTAMP);
857+ this.tsValue = value;
858+ }
859+ @Override
860+ void appendTo(Insert.Options usings) {
861+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
862+ }
863+ @Override
864+ void appendTo(Delete.Options usings) {
865+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
866+ }
867+ @Override
868+ void checkValidFor(QueryType qt, MappingManager manager) {
869+ checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
870+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
871+ }
872+ @Override
873+ void addToPreparedStatement(BoundStatement bs, int i) {
874+ bs.setLong(i, this.tsValue);
875+ }
876+ @Override
877+ boolean isIncludedInQuery() {
878+ return true;
879+ }
880+ }
881+
882+ static class ConsistencyLevelOption extends Option {
883+
884+ private ConsistencyLevel cl;
885+
886+ ConsistencyLevelOption(ConsistencyLevel cl) {
887+ super(Type.CL);
888+ this.cl = cl;
889+ }
890+ @Override
891+ void appendTo(Insert.Options usings) {
892+ throw new UnsupportedOperationException("shouldn't be called");
893+ }
894+ @Override
895+ void appendTo(Delete.Options usings) {
896+ throw new UnsupportedOperationException("shouldn't be called");
897+ }
898+
899+ @Override
900+ void addToPreparedStatement(BoundStatement bs, int i) {
901+ bs.setConsistencyLevel(cl);
902+ }
903+ @Override
904+ void checkValidFor(QueryType qt, MappingManager manager) {
905+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
906+ "Consistency level option is only allowed in save, delete and get queries");
907+ }
908+
909+ @Override
910+ boolean isIncludedInQuery() {
911+ return false;
912+ }
913+ }
914+
915+ static class Tracing extends Option {
916+
917+ private boolean tracing;
918+
919+ Tracing(boolean tracing) {
920+ super(Type.TRACING);
921+ this.tracing = tracing;
922+ }
923+ @Override
924+ void appendTo(Insert.Options usings) {
925+ throw new UnsupportedOperationException("shouldn't be called");
926+ }
927+ @Override
928+ void appendTo(Delete.Options usings) {
929+ throw new UnsupportedOperationException("shouldn't be called");
930+ }
931+
932+ @Override
933+ void addToPreparedStatement(BoundStatement bs, int i) {
934+ if (this.tracing)
935+ bs.enableTracing();
936+ }
937+
938+ @Override
939+ void checkValidFor(QueryType qt, MappingManager manager) {
940+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
941+ "Tracing option is only allowed in save, delete and get queries");
942+ }
943+
944+ @Override
945+ boolean isIncludedInQuery() {
946+ return false;
947+ }
948+ }
949+
950+ static class SaveNullFields extends Option {
951+
952+ private boolean saveNullFields;
953+
954+ SaveNullFields(boolean saveNullFields) {
955+ super(SAVE_NULL_FIELDS);
956+ this.saveNullFields = saveNullFields;
957+ }
958+
959+ @Override
960+ void appendTo(Insert.Options usings) {
961+ throw new UnsupportedOperationException("shouldn't be called");
962+ }
963+
964+ @Override
965+ void appendTo(Delete.Options usings) {
966+ throw new UnsupportedOperationException("shouldn't be called");
967+ }
968+
969+ @Override
970+ void addToPreparedStatement(BoundStatement bs, int i) {
971+ // nothing to do
972+ }
973+
974+ @Override
975+ void checkValidFor(QueryType qt, MappingManager manager) {
976+ checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
977+ }
978+
979+ @Override
980+ boolean isIncludedInQuery() {
981+ return false;
982+ }
983+ }
984+
985+ }
986+
987+ private static class MapperQueryKey {
988+ private final QueryType queryType;
989+ private final EnumSet<Option.Type> optionTypes;
990+ private final Set<ColumnMapper<?>> columns;
991+
992+ MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
993+ Preconditions.checkNotNull(queryType);
994+ Preconditions.checkNotNull(options);
995+ Preconditions.checkNotNull(columnMappers);
996+ this.queryType = queryType;
997+ this.columns = columnMappers;
998+ this.optionTypes = EnumSet.noneOf(Option.Type.class);
999+ for (Option opt : options.values()) {
1000+ if (opt.isIncludedInQuery())
1001+ this.optionTypes.add(opt.type);
1002+ }
1003+ }
1004+
1005+ @Override
1006+ public boolean equals(Object other) {
1007+ if (this == other)
1008+ return true;
1009+ if (other instanceof MapperQueryKey) {
1010+ MapperQueryKey that = (MapperQueryKey)other;
1011+ return this.queryType.equals(that.queryType)
1012+ && this.optionTypes.equals(that.optionTypes)
1013+ && this.columns.equals(that.columns);
1014+ }
1015+ return false;
1016+ }
1017+
1018+ public int hashCode() {
1019+ return Objects.hashCode(queryType, optionTypes, columns);
1020+ }
4061021 }
4071022 }
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 +96 −80
@@ -16,7 +16,9 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.util.ArrayList;
19+import java.util.Collection;
1920 import java.util.List;
21+import java.util.Set;
2022
2123 import com.google.common.base.Objects;
2224
@@ -29,7 +31,8 @@
2931
3032 class QueryType {
3133
32- private enum Kind { SAVE, GET, DEL, SLICE, REVERSED_SLICE };
34+ private enum Kind {SAVE, GET, DEL, SLICE, REVERSED_SLICE}
35+
3336 private final Kind kind;
3437
3538 // For slices
@@ -58,100 +61,112 @@
5861 return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
5962 }
6063
61- String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper) {
64+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
6265 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();
66+ case SAVE: {
67+ Insert insert = table == null
68+ ? insertInto(mapper.getKeyspace(), mapper.getTable())
69+ : insertInto(table);
70+ for (ColumnMapper<?> cm : columns)
71+ if (cm.kind != ColumnMapper.Kind.COMPUTED)
72+ insert.value(cm.getColumnName(), bindMarker());
73+
74+ Insert.Options usings = insert.using();
75+ for (Mapper.Option opt : options) {
76+ opt.checkValidFor(QueryType.SAVE, manager);
77+ if (opt.isIncludedInQuery())
78+ opt.appendTo(usings);
7279 }
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());
80+ return insert.toString();
81+ }
82+ case GET: {
83+ Select.Selection selection = select();
84+ for (ColumnMapper cm : mapper.allColumns()) {
85+ Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
86+ ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
87+ : selection.column(cm.getColumnName());
88+
89+ if (cm.getAlias() == null) {
90+ selection = column;
9091 } else {
91- select = selection.from(table);
92+ selection = column.as(cm.getAlias());
9293 }
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();
9794 }
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();
95+ Select select;
96+ if (table == null) {
97+ select = selection.from(mapper.getKeyspace(), mapper.getTable());
98+ } else {
99+ select = selection.from(table);
107100 }
101+ Select.Where where = select.where();
102+ for (int i = 0; i < mapper.primaryKeySize(); i++)
103+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
104+
105+ for (Mapper.Option opt : options)
106+ opt.checkValidFor(QueryType.GET, manager);
107+ return select.toString();
108+ }
109+ case DEL: {
110+ Delete delete = table == null
111+ ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
112+ : delete().all().from(table);
113+ Delete.Where where = delete.where();
114+ for (int i = 0; i < mapper.primaryKeySize(); i++)
115+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
116+ Delete.Options usings = delete.using();
117+ for (Mapper.Option opt : options) {
118+ opt.checkValidFor(QueryType.DEL, manager);
119+ if (opt.isIncludedInQuery())
120+ opt.appendTo(usings);
121+ }
122+ return delete.toString();
123+ }
108124 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));
125+ case REVERSED_SLICE: {
126+ Select select = table == null
127+ ? select().all().from(mapper.getKeyspace(), mapper.getTable())
128+ : select().all().from(table);
129+ Select.Where where = select.where();
130+ for (int i = 0; i < mapper.partitionKeys.size(); i++)
131+ where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
132+
133+ if (startBoundSize > 0) {
134+ if (startBoundSize == 1) {
135+ String name = mapper.clusteringColumns.get(0).getColumnName();
136+ where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
137+ } else {
138+ List<String> names = new ArrayList<String>(startBoundSize);
139+ List<Object> values = new ArrayList<Object>(startBoundSize);
140+ for (int i = 0; i < startBoundSize; i++) {
141+ names.add(mapper.clusteringColumns.get(i).getColumnName());
142+ values.add(bindMarker());
130143 }
144+ where.and(startInclusive ? gte(names, values) : gt(names, values));
131145 }
146+ }
132147
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));
148+ if (endBoundSize > 0) {
149+ if (endBoundSize == 1) {
150+ String name = mapper.clusteringColumns.get(0).getColumnName();
151+ where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
152+ } else {
153+ List<String> names = new ArrayList<String>(endBoundSize);
154+ List<Object> values = new ArrayList<Object>(endBoundSize);
155+ for (int i = 0; i < endBoundSize; i++) {
156+ names.add(mapper.clusteringColumns.get(i).getColumnName());
157+ values.add(bindMarker());
145158 }
159+ where.and(endInclusive ? lte(names, values) : lt(names, values));
146160 }
161+ }
147162
148- select = select.limit(bindMarker());
163+ select = select.limit(bindMarker());
149164
150- if (kind == Kind.REVERSED_SLICE)
151- select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
165+ if (kind == Kind.REVERSED_SLICE)
166+ select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
152167
153- return select.toString();
154- }
168+ return select.toString();
169+ }
155170 }
156171 throw new AssertionError();
157172 }
@@ -175,4 +190,5 @@
175190 public int hashCode() {
176191 return Objects.hashCode(kind, startBoundSize, startInclusive, endBoundSize, endInclusive);
177192 }
193+
178194 }
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)));
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +19 −1
@@ -18,9 +18,11 @@
1818 import java.util.Collection;
1919
2020 import com.google.common.collect.Lists;
21+import org.testng.SkipException;
2122 import org.testng.annotations.BeforeMethod;
2223 import org.testng.annotations.Test;
2324
25+import static com.datastax.driver.core.ProtocolVersion.V1;
2426 import static org.assertj.core.api.Assertions.fail;
2527
2628 import com.datastax.driver.core.*;
@@ -35,7 +37,6 @@
3537 * annotation to map computed fields.
3638 */
3739 @SuppressWarnings("unused")
38-@CassandraVersion(major = 2.0)
3940 public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
4041
4142 @Override
@@ -45,16 +46,28 @@
4546 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
4647 }
4748
49+ ProtocolVersion protocolVersion;
4850 MappingManager mappingManager;
4951 Mapper<User> userMapper;
5052
5153 @BeforeMethod(groups = "short")
5254 void setup() {
5355 mappingManager = new MappingManager(session);
56+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
57+ if (protocolVersion.compareTo(V1) > 0)
58+ userMapper = mappingManager.mapper(User.class);
59+ }
60+
61+ @Test(groups = "short", expectedExceptions = { UnsupportedOperationException.class })
62+ void should_get_unsupported_operation_exception_on_v1() {
63+ if (protocolVersion.compareTo(V1) > 0)
64+ throw new SkipException("Skipped when protocol version > V1");
65+
5466 userMapper = mappingManager.mapper(User.class);
5567 }
5668
5769 @Test(groups = "short")
70+ @CassandraVersion(major = 2.0)
5871 void should_save_and_get_entity_with_computed_fields() {
5972 long writeTime = System.currentTimeMillis() * 1000;
6073 User newUser = new User("testlogin2", "blah");
@@ -80,6 +93,7 @@
8093 }
8194
8295 @Test(groups = "short")
96+ @CassandraVersion(major = 2.0)
8397 void should_add_aliases_for_fields_in_select_queries() {
8498 BoundStatement bs = (BoundStatement)userMapper.getQuery("test");
8599 assertThat(bs.preparedStatement().getQueryString())
@@ -87,6 +101,7 @@
87101 }
88102
89103 @Test(groups = "short")
104+ @CassandraVersion(major = 2.0)
90105 public void should_map_aliased_resultset_to_objects() {
91106 Statement getQuery = userMapper.getQuery("testlogin");
92107 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
@@ -99,6 +114,7 @@
99114 }
100115
101116 @Test(groups = "short")
117+ @CassandraVersion(major = 2.0)
102118 void should_map_unaliased_resultset_to_objects() {
103119 UserAccessor userAccessor = mappingManager.createAccessor(UserAccessor.class);
104120 ResultSet rs = userAccessor.all();
@@ -110,11 +126,13 @@
110126 }
111127
112128 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
129+ @CassandraVersion(major = 2.0)
113130 void should_fail_if_computed_field_is_not_right_type() {
114131 mappingManager.mapper(User_WrongComputedType.class);
115132 }
116133
117134 @Test(groups = "short")
135+ @CassandraVersion(major = 2.0)
118136 void should_fail_if_computed_field_marked_with_column_annotation() {
119137 Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
120138 try {
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +397 −0
@@ -0,0 +1,397 @@
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 com.datastax.driver.core.ConsistencyLevel.*;
27+import static org.assertj.core.api.Assertions.assertThat;
28+import static org.assertj.core.api.Assertions.fail;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.exceptions.NoHostAvailableException;
32+import com.datastax.driver.core.exceptions.UnavailableException;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+import com.datastax.driver.mapping.annotations.PartitionKey;
35+import com.datastax.driver.mapping.annotations.Table;
36+
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() throws Exception {
59+ Long tsValue = futureTimestamp();
60+ mapper.save(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(QUORUM));
73+ assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
74+ assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
75+ }
76+
77+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
78+ @CassandraVersion(major = 2.0)
79+ void should_use_get_options() {
80+ User user = new User(45, "toget");
81+ mapper.save(user);
82+
83+ BoundStatement bs = (BoundStatement)mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
84+ assertThat(bs.isTracing()).isTrue();
85+ assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
86+
87+ ResultSet rs = session.execute(bs);
88+ assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
89+ User us = mapper.mapAliased(rs).one();
90+ assertThat(us.getV()).isEqualTo("toget");
91+
92+ mapper.getQuery(45, Option.timestamp(1337));
93+ }
94+
95+ @Test(groups = "short")
96+ @CassandraVersion(major = 2.0)
97+ void should_use_options_only_once() {
98+ Long tsValue = futureTimestamp();
99+ mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
100+ mapper.save(new User(44, "test"));
101+ Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
102+ // Assuming we cannot go back in time (yet) and execute the write at ts=1
103+ assertThat(tsReturned).isNotEqualTo(tsValue);
104+ }
105+
106+ @Test(groups = "short")
107+ @CassandraVersion(major = 2.0)
108+ void should_use_default_options() {
109+ mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
110+ BoundStatement bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"));
111+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
112+
113+ mapper.resetDefaultSaveOptions();
114+ bs = (BoundStatement)mapper.saveQuery(new User(47, "rjhrgce"));
115+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
116+
117+ mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
118+ bs = (BoundStatement)mapper.deleteQuery(47);
119+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
120+ assertThat(bs.isTracing()).isTrue();
121+
122+ mapper.resetDefaultDeleteOptions();
123+ bs = (BoundStatement)mapper.deleteQuery(47);
124+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
125+ assertThat(bs.isTracing()).isFalse();
126+
127+ bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
128+ assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
129+
130+ mapper.setDefaultGetOptions(Option.tracing(true));
131+ bs = (BoundStatement)mapper.getQuery(46);
132+ assertThat(bs.isTracing()).isTrue();
133+
134+ mapper.resetDefaultGetOptions();
135+ bs = (BoundStatement)mapper.getQuery(46);
136+ assertThat(bs.isTracing()).isFalse();
137+ }
138+
139+ @Test(groups = "short")
140+ @CassandraVersion(major = 2.0)
141+ void should_prioritize_option_over_model_consistency() {
142+ // Generate Write Query and ensure User model writeConsistency is used.
143+ User user = new User(1859, "Steve");
144+ Statement saveDefault = mapper.saveQuery(user);
145+ assertThat(saveDefault.getConsistencyLevel()).isEqualTo(ONE);
146+
147+ // Generate Write Query and ensure provided Option for consistencyLevel is used.
148+ Statement saveProvidedCL = mapper.saveQuery(user, Option.consistencyLevel(QUORUM));
149+ assertThat(saveProvidedCL.getConsistencyLevel()).isEqualTo(QUORUM);
150+
151+ // Generate Read Query and ensure User model readConsistency is used.
152+ Statement readDefault = mapper.getQuery(1859);
153+ assertThat(readDefault.getConsistencyLevel()).isEqualTo(LOCAL_ONE);
154+
155+ // Generate Ready Query and ensure provided Option for consistencyLevel is used.
156+ Statement readProvidedCL = mapper.getQuery(1859, Option.consistencyLevel(LOCAL_QUORUM));
157+ assertThat(readProvidedCL.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
158+ }
159+
160+ @Test(groups = "short")
161+ @CassandraVersion(major = 2.0)
162+ void should_use_explicit_options_over_default_options() {
163+ long defaultTimestamp = futureTimestamp();
164+ long explicitTimestamp = futureTimestamp();
165+
166+ mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
167+
168+ mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
169+ Long savedTimestamp = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
170+ assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
171+ }
172+
173+ /** Cover all versions of save() to check that methods that call each other properly propagate the options */
174+ @Test(groups = "short")
175+ @CassandraVersion(major = 2.0)
176+ void should_use_save_options_for_all_variants() throws ExecutionException, InterruptedException {
177+ Long timestamp = futureTimestamp();
178+ User user = new User(42, "helloworld");
179+
180+ mapper.save(user, Option.timestamp(timestamp));
181+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
182+ mapper.delete(user.getKey());
183+
184+ mapper.saveAsync(user, Option.timestamp(timestamp)).get();
185+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
186+ mapper.delete(user.getKey());
187+
188+ session.execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
189+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
190+ mapper.delete(user.getKey());
191+
192+ // Set as default and try optionless methods
193+ mapper.setDefaultSaveOptions(Option.timestamp(timestamp));
194+
195+ mapper.save(user);
196+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
197+ mapper.delete(user.getKey());
198+
199+ mapper.saveAsync(user).get();
200+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
201+ mapper.delete(user.getKey());
202+
203+ session.execute(mapper.saveQuery(user));
204+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
205+ mapper.delete(user.getKey());
206+ }
207+
208+ private Long getWriteTime(int key) {
209+ Row row = session.execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
210+ return row.getLong(0);
211+ }
212+
213+ @Test(groups = "short")
214+ @CassandraVersion(major = 2.0)
215+ void should_use_get_options_for_all_variants() throws InterruptedException {
216+ try {
217+ mapper.get(42, Option.consistencyLevel(TWO));
218+ fail("Expected a NoHostAvailableException");
219+ } catch (NoHostAvailableException e) {
220+ assertFirstNodeUnavailable(e);
221+ }
222+
223+ try {
224+ mapper.getAsync(42, Option.consistencyLevel(TWO)).get();
225+ fail("Expected an ExecutionException");
226+ } catch (ExecutionException e) {
227+ assertFirstNodeUnavailable(e);
228+ }
229+
230+ Statement statement = mapper.getQuery(42, Option.consistencyLevel(TWO));
231+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
232+
233+ // Set as default and try optionless methods
234+ mapper.setDefaultGetOptions(Option.consistencyLevel(TWO));
235+
236+ try {
237+ mapper.get(42);
238+ fail("Expected a NoHostAvailableException");
239+ } catch (NoHostAvailableException e) {
240+ assertFirstNodeUnavailable(e);
241+ }
242+
243+ try {
244+ mapper.getAsync(42).get();
245+ fail("Expected an ExecutionException");
246+ } catch (ExecutionException e) {
247+ assertFirstNodeUnavailable(e);
248+ }
249+
250+ statement = mapper.getQuery(42);
251+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
252+ }
253+
254+ @Test(groups = "short")
255+ @CassandraVersion(major = 2.0)
256+ void should_use_delete_options_for_all_variants() throws InterruptedException {
257+ User user = new User(42, "helloworld");
258+
259+ try {
260+ mapper.delete(user, Option.consistencyLevel(TWO));
261+ fail("Expected a NoHostAvailableException");
262+ } catch (NoHostAvailableException e) {
263+ assertFirstNodeUnavailable(e);
264+ }
265+
266+ try {
267+ mapper.deleteAsync(user, Option.consistencyLevel(TWO)).get();
268+ fail("Expected an ExecutionException");
269+ } catch (ExecutionException e) {
270+ assertFirstNodeUnavailable(e);
271+ }
272+
273+ Statement statement = mapper.deleteQuery(user, Option.consistencyLevel(TWO));
274+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
275+
276+ try {
277+ mapper.delete(user.getKey(), Option.consistencyLevel(TWO));
278+ fail("Expected a NoHostAvailableException");
279+ } catch (NoHostAvailableException e) {
280+ assertFirstNodeUnavailable(e);
281+ }
282+
283+ try {
284+ mapper.deleteAsync(user.getKey(), Option.consistencyLevel(TWO)).get();
285+ fail("Expected an ExecutionException");
286+ } catch (ExecutionException e) {
287+ assertFirstNodeUnavailable(e);
288+ }
289+
290+ statement = mapper.deleteQuery(user.getKey(), Option.consistencyLevel(TWO));
291+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
292+
293+ // Set as default and try optionless methods
294+ mapper.setDefaultDeleteOptions(Option.consistencyLevel(TWO));
295+
296+ try {
297+ mapper.delete(user);
298+ fail("Expected a NoHostAvailableException");
299+ } catch (NoHostAvailableException e) {
300+ assertFirstNodeUnavailable(e);
301+ }
302+
303+ try {
304+ mapper.deleteAsync(user).get();
305+ fail("Expected an ExecutionException");
306+ } catch (ExecutionException e) {
307+ assertFirstNodeUnavailable(e);
308+ }
309+
310+ statement = mapper.deleteQuery(user);
311+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
312+
313+ try {
314+ mapper.delete(user.getKey());
315+ fail("Expected a NoHostAvailableException");
316+ } catch (NoHostAvailableException e) {
317+ assertFirstNodeUnavailable(e);
318+ }
319+
320+ try {
321+ mapper.deleteAsync(user.getKey()).get();
322+ fail("Expected an ExecutionException");
323+ } catch (ExecutionException e) {
324+ assertFirstNodeUnavailable(e);
325+ }
326+
327+ statement = mapper.deleteQuery(user.getKey());
328+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
329+ }
330+
331+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
332+ void should_fail_if_option_does_not_apply_to_query() {
333+ mapper.get(42, Option.ttl(1));
334+ }
335+
336+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
337+ void should_fail_when_using_ttl_with_protocol_v1() {
338+ if (protocolVersion.compareTo(V1) > 0)
339+ throw new SkipException("Skipped when protocol version > V1");
340+
341+ mapper.saveQuery(new User(42, "helloworld"), Option.ttl(15));
342+ }
343+
344+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
345+ void should_fail_when_using_timestamp_with_protocol_v1() {
346+ if (protocolVersion.compareTo(V1) > 0)
347+ throw new SkipException("Skipped when protocol version > V1");
348+
349+ mapper.saveQuery(new User(42, "helloworld"), Option.timestamp(15));
350+ }
351+
352+ private static void assertFirstNodeUnavailable(NoHostAvailableException e) {
353+ Throwable node1Error = e.getErrors().values().iterator().next();
354+ assertThat(node1Error).isInstanceOf(UnavailableException.class);
355+ }
356+
357+ private static void assertFirstNodeUnavailable(ExecutionException e) {
358+ Throwable cause = e.getCause();
359+ assertThat(cause).isInstanceOf(NoHostAvailableException.class);
360+ assertFirstNodeUnavailable((NoHostAvailableException) cause);
361+ }
362+
363+ private static long futureTimestamp() {
364+ return (System.currentTimeMillis() + 1000) * 1000;
365+ }
366+
367+ @Table(name = "user", readConsistency = "LOCAL_ONE", writeConsistency = "ONE")
368+ public static class User {
369+ @PartitionKey
370+ private int key;
371+ private String v;
372+
373+ public User() {
374+ }
375+
376+ public User(int k, String val) {
377+ this.key = k;
378+ this.v = val;
379+ }
380+
381+ public int getKey() {
382+ return this.key;
383+ }
384+
385+ public void setKey(int pk) {
386+ this.key = pk;
387+ }
388+
389+ public String getV() {
390+ return this.v;
391+ }
392+
393+ public void setV(String val) {
394+ this.v = val;
395+ }
396+ }
397+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +151 −0
@@ -0,0 +1,151 @@
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+
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.BoundStatement;
27+import com.datastax.driver.core.CCMBridge;
28+import com.datastax.driver.mapping.Mapper.Option;
29+import com.datastax.driver.mapping.annotations.PartitionKey;
30+import com.datastax.driver.mapping.annotations.Table;
31+
32+public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ Mapper<User> mapper;
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)");
39+ }
40+
41+ @BeforeMethod(groups = "short")
42+ public void setup() {
43+ mapper = new MappingManager(session).mapper(User.class);
44+ }
45+
46+ @Test(groups = "short")
47+ void should_save_null_fields_if_requested() {
48+ should_save_null_fields(true, Option.saveNullFields(true));
49+
50+ mapper.setDefaultSaveOptions(Option.saveNullFields(true));
51+ should_save_null_fields(true);
52+ }
53+
54+ @Test(groups = "short")
55+ void should_save_null_fields_by_default() {
56+ should_save_null_fields(true);
57+ }
58+
59+ @Test(groups = "short")
60+ void should_ignore_null_fields_if_requested() {
61+ should_save_null_fields(false, Option.saveNullFields(false));
62+
63+ mapper.setDefaultSaveOptions(Option.saveNullFields(false));
64+ should_save_null_fields(false);
65+ }
66+
67+ private void should_save_null_fields(boolean saveExpected, Option... options) {
68+ // Try different combinations of null fields
69+ should_save_null_fields(true, true, saveExpected, options);
70+ should_save_null_fields(true, false, saveExpected, options);
71+ should_save_null_fields(false, true, saveExpected, options);
72+ should_save_null_fields(false, false, saveExpected, options);
73+ }
74+
75+ private void should_save_null_fields(boolean nullName, boolean nullPhone, boolean saveExpected, Option... options) {
76+ // Start with clean data
77+ session.execute("insert into user(login, name, phone) "
78+ + "values ('test_login', 'previous_name', 'previous_phone')");
79+
80+ String newName = nullName ? null : "new_name";
81+ String newPhone = nullPhone ? null : "new_phone";
82+ String description = String.format("update with name=%s, phone = %s", newName, newPhone);
83+ User newUser = new User("test_login", newName, newPhone);
84+
85+ // Check if null fields are included in generated statement:
86+ BoundStatement bs = (BoundStatement)mapper.saveQuery(newUser, options);
87+ String queryString = bs.preparedStatement().getQueryString();
88+ if (nullName && !saveExpected)
89+ assertThat(queryString).as(description).doesNotContain("\"name\"");
90+ else
91+ assertThat(queryString).as(description).contains("\"name\"");
92+
93+ if (nullPhone && !saveExpected)
94+ assertThat(queryString).as(description).doesNotContain("\"phone\"");
95+ else
96+ assertThat(queryString).as(description).contains("\"phone\"");
97+
98+ // Save entity and check the data
99+ mapper.save(newUser, options);
100+ User savedUser = mapper.get("test_login");
101+ String expectedName = nullName
102+ ? (saveExpected ? null : "previous_name")
103+ : "new_name";
104+ String expectedPhone = nullPhone
105+ ? (saveExpected ? null : "previous_phone")
106+ : "new_phone";
107+ assertThat(savedUser.getName()).as(description).isEqualTo(expectedName);
108+ assertThat(savedUser.getPhone()).as(description).isEqualTo(expectedPhone);
109+ }
110+
111+ @Table(name = "user")
112+ public static class User {
113+ @PartitionKey
114+ private String login;
115+ private String name;
116+ private String phone;
117+
118+ public User() {
119+ }
120+
121+ public User(String login, String name, String phone) {
122+ this.login = login;
123+ this.name = name;
124+ this.phone = phone;
125+ }
126+
127+ public String getLogin() {
128+ return login;
129+ }
130+
131+ public void setLogin(String login) {
132+ this.login = login;
133+ }
134+
135+ public String getName() {
136+ return name;
137+ }
138+
139+ public void setName(String name) {
140+ this.name = name;
141+ }
142+
143+ public String getPhone() {
144+ return phone;
145+ }
146+
147+ public void setPhone(String phone) {
148+ this.phone = phone;
149+ }
150+ }
151+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +13 −0
@@ -418,4 +418,17 @@
418418 // cleanup
419419 session.execute("delete from posts where user_id = " + u1.getUserId());
420420 }
421+
422+ @Test(groups="short")
423+ public void should_not_initialize_session_when_protocol_version_provided() {
424+ Session newSession = cluster.newSession();
425+
426+ // Ensures that a Session is not initialized when a protocol version is provided.
427+ MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
428+ assertThat(newSession.getState().getConnectedHosts()).hasSize(0);
429+
430+ // Session should be initialized on first query.
431+ newSession.execute("USE " + keyspace);
432+ assertThat(newSession.getState().getConnectedHosts()).hasSize(1);
433+ }
421434 }
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