Elffuss BraidHub

kikocis/java-driver public

Provide a way to map computed fields (JAVA-661).

Also :
- Behaviour change for Mapper.get() method which now selects each field
  of the mapped class and adds aliases
- QueryBuilder added methods to produce select queries without checking
  validity of the column names (raw column names)
Changeset1b19082d891d92079dd2ec69e035e0f91e173041d5daf777a3c054d4f3ffbdcb
AuthorKevin Gallardo <kevin.gallardo@datastax.com> · 2015-05-21 11:53 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-06-26 18:19 +02:00
Parentse2d5e12472e5

Browse the files at this changeset

15 files changed

modified changelog/README.md +1 −0
@@ -17,6 +17,7 @@
1717 - [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688)
1818 - [improvement] Allow @Enumerated in Accessor method parameters (JAVA-589)
1919 - [improvement] Allow access to table metadata from Mapper (JAVA-554)
20+- [improvement] Provide a way to map computed fields (JAVA-661)
2021
2122
2223 ### 2.1.6
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +13 −0
@@ -347,6 +347,14 @@
347347 */
348348 public abstract SelectionOrAlias column(String name);
349349
350+ /**
351+ * Selects the provided raw expression.
352+ *
353+ * @param rawString the raw expression to add.
354+ * @return this in-build SELECT statement
355+ */
356+ public abstract SelectionOrAlias raw(String rawString);
357+
350358 /**
351359 * Selects the write time of provided column.
352360 * <p>
@@ -470,6 +478,11 @@
470478 return queueName(name);
471479 }
472480
481+ @Override
482+ public SelectionOrAlias raw(String rawString) {
483+ return queueName(QueryBuilder.raw(rawString));
484+ }
485+
473486 /**
474487 * Selects the write time of provided column.
475488 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +2 −0
@@ -307,6 +307,8 @@
307307 Alias alias = (Alias)name;
308308 appendName(alias.column, sb);
309309 sb.append(" AS ").append(alias.alias);
310+ } else if (name instanceof RawString) {
311+ sb.append(((RawString)name).str);
310312 } else {
311313 throw new IllegalArgumentException(String.format("Invalid column %s of type unknown of the query builder", name));
312314 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +8 −0
@@ -75,6 +75,7 @@
7575 field.getDeclaringClass().getName(), e.getMessage()));
7676 }
7777 }
78+ checkValidComputed(field);
7879 }
7980
8081 // Returns the offending annotation if there is one
@@ -100,6 +101,13 @@
100101 checkFrozenTypes(javaType, declaredFrozenType);
101102 }
102103
104+ static void checkValidComputed(Field field) {
105+ Computed computed = field.getAnnotation(Computed.class);
106+ if (computed != null && computed.formula().isEmpty()){
107+ throw new IllegalArgumentException(String.format("Field %s: attribute 'formula' of annotation @Computed is mandatory for computed fields", field.getName()));
108+ }
109+ }
110+
103111 // Builds a DeclaredFrozenType hierarchy based on the @Frozen* annotations on a field.
104112 private static DeclaredFrozenType getDeclaredFrozenType(Field field) {
105113 Frozen frozen = field.getAnnotation(Frozen.class);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +34 −10
@@ -22,6 +22,7 @@
2222 import java.util.Collections;
2323 import java.util.Comparator;
2424 import java.util.List;
25+import java.util.concurrent.atomic.AtomicInteger;
2526
2627 import com.google.common.base.Strings;
2728
@@ -76,7 +77,7 @@
7677
7778 AnnotationChecks.validateAnnotations(field, "entity",
7879 Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
79- FrozenValue.class, PartitionKey.class, Transient.class);
80+ FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
8081
8182 if (field.getAnnotation(Transient.class) != null)
8283 continue;
@@ -94,15 +95,17 @@
9495 }
9596 }
9697
98+ AtomicInteger columnCounter = new AtomicInteger(0);
99+
97100 Collections.sort(pks, fieldComparator);
98101 Collections.sort(ccs, fieldComparator);
99102
100103 validateOrder(pks, "@PartitionKey");
101104 validateOrder(ccs, "@ClusteringColumn");
102105
103- mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager),
104- convert(ccs, factory, mapper.entityClass, mappingManager),
105- convert(rgs, factory, mapper.entityClass, mappingManager));
106+ mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager, columnCounter),
107+ convert(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
108+ convert(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
106109 return mapper;
107110 }
108111
@@ -148,16 +151,16 @@
148151 }
149152 }
150153
151- mapper.addColumns(convert(columns, factory, udtClass, mappingManager));
154+ mapper.addColumns(convert(columns, factory, udtClass, mappingManager, null));
152155 return mapper;
153156 }
154157
155- private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager) {
158+ private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
156159 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
157160 for (int i = 0; i < fields.size(); i++) {
158161 Field field = fields.get(i);
159162 int pos = position(field);
160- mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager));
163+ mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
161164 }
162165 return mappers;
163166 }
@@ -186,12 +189,20 @@
186189 public static ColumnMapper.Kind kind(Field field) {
187190 PartitionKey pk = field.getAnnotation(PartitionKey.class);
188191 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
192+ Computed comp = field.getAnnotation(Computed.class);
189193 if (pk != null && cc != null)
190194 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
191195
192- return pk != null
193- ? ColumnMapper.Kind.PARTITION_KEY
194- : (cc != null ? ColumnMapper.Kind.CLUSTERING_COLUMN : ColumnMapper.Kind.REGULAR);
196+ if (pk != null) {
197+ return ColumnMapper.Kind.PARTITION_KEY;
198+ }
199+ if (cc != null) {
200+ return ColumnMapper.Kind.CLUSTERING_COLUMN;
201+ }
202+ if (comp != null) {
203+ return ColumnMapper.Kind.COMPUTED;
204+ }
205+ return ColumnMapper.Kind.REGULAR;
195206 }
196207
197208 public static EnumType enumType(Field field) {
@@ -205,7 +216,11 @@
205216
206217 public static String columnName(Field field) {
207218 Column column = field.getAnnotation(Column.class);
219+ Computed computedField = field.getAnnotation(Computed.class);
208220 if (column != null && !column.name().isEmpty()) {
221+ if (computedField != null){
222+ throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
223+ }
209224 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
210225 }
211226
@@ -214,9 +229,18 @@
214229 return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
215230 }
216231
232+ if (computedField != null) {
233+ return computedField.formula();
234+ }
235+
217236 return field.getName().toLowerCase();
218237 }
219238
239+ public static String newAlias(Field field, int columnNumber) {
240+ return "col" + columnNumber;
241+
242+ }
243+
220244 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
221245 if (!accClass.isInterface())
222246 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +20 −11
@@ -16,15 +16,18 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.lang.reflect.Field;
19+import java.util.concurrent.atomic.AtomicInteger;
1920
2021 import com.datastax.driver.core.DataType;
22+
2123 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
2224
2325 abstract class ColumnMapper<T> {
2426
25- public enum Kind { PARTITION_KEY, CLUSTERING_COLUMN, REGULAR };
27+ public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED};
2628
2729 private final String columnName;
30+ private final String alias;
2831 protected final String fieldName;
2932 protected final Class<?> javaType;
3033 // Note: dataType is not guaranteed to be exact. Typically, it will be uuid even if the underlying
@@ -34,24 +37,30 @@
3437 protected final Kind kind;
3538 protected final int position;
3639
37- protected ColumnMapper(Field field, DataType dataType, int position) {
38- this(AnnotationParser.columnName(field), field.getName(), field.getType(), dataType, AnnotationParser.kind(field), position);
39- }
40-
41- private ColumnMapper(String columnName, String fieldName, Class<?> javaType, DataType dataType, Kind kind, int position) {
42- this.columnName = columnName;
43- this.fieldName = fieldName;
44- this.javaType = javaType;
40+ protected ColumnMapper(Field field, DataType dataType, int position, AtomicInteger columnCounter) {
41+ this.columnName = AnnotationParser.columnName(field);
42+ this.alias = (columnCounter != null)
43+ ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
44+ : null;
45+ this.fieldName = field.getName();
46+ this.javaType = field.getType();
4547 this.dataType = dataType;
46- this.kind = kind;
48+ this.kind = AnnotationParser.kind(field);
4749 this.position = position;
4850 }
4951
5052 public abstract Object getValue(T entity);
53+
5154 public abstract void setValue(T entity, Object value);
5255
5356 public String getColumnName() {
54- return quote(columnName);
57+ return kind == Kind.COMPUTED
58+ ? columnName
59+ : quote(columnName);
60+ }
61+
62+ public String getAlias() {
63+ return alias;
5564 }
5665
5766 public DataType getDataType() {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +2 −1
@@ -17,6 +17,7 @@
1717
1818 import java.lang.reflect.Field;
1919 import java.util.*;
20+import java.util.concurrent.atomic.AtomicInteger;
2021
2122 import com.datastax.driver.core.ConsistencyLevel;
2223 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
@@ -83,6 +84,6 @@
8384
8485 interface Factory {
8586 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency);
86- public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager);
87+ public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter);
8788 }
8889 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +41 −7
@@ -23,11 +23,12 @@
2323 import com.google.common.base.Functions;
2424 import com.google.common.util.concurrent.Futures;
2525 import com.google.common.util.concurrent.ListenableFuture;
26-
2726 import org.slf4j.Logger;
2827 import org.slf4j.LoggerFactory;
2928
3029 import com.datastax.driver.core.*;
30+import com.datastax.driver.mapping.annotations.Computed;
31+import com.datastax.driver.mapping.annotations.Accessor;
3132
3233 /**
3334 * An object handling the mapping of a particular class.
@@ -51,7 +52,8 @@
5152 private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
5253
5354 final Function<ResultSet, T> mapOneFunction;
54- final Function<ResultSet, Result<T>> mapAllFunction;
55+ final Function<ResultSet, T> mapOneFunctionWithoutAliases;
56+ final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
5557
5658 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
5759 this.manager = manager;
@@ -63,11 +65,16 @@
6365
6466 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersionEnum();
6567 this.mapOneFunction = new Function<ResultSet, T>() {
68+ public T apply(ResultSet rs) {
69+ return Mapper.this.mapAliased(rs).one();
70+ }
71+ };
72+ this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
6673 public T apply(ResultSet rs) {
6774 return Mapper.this.map(rs).one();
6875 }
6976 };
70- this.mapAllFunction = new Function<ResultSet, Result<T>>() {
77+ this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
7178 public Result<T> apply(ResultSet rs) {
7279 return Mapper.this.map(rs);
7380 }
@@ -132,8 +139,10 @@
132139 BoundStatement bs = ps.bind();
133140 int i = 0;
134141 for (ColumnMapper<T> cm : mapper.allColumns()) {
135- Object value = cm.getValue(entity);
136- bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
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));
145+ }
137146 }
138147
139148 if (mapper.writeConsistency != null)
@@ -284,18 +293,43 @@
284293 }
285294
286295 /**
287- * Map the rows from a {@code ResultSet} into the class this is mapper of.
296+ * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
297+ * <p>
298+ * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
299+ * manual query or an {@link Accessor method}.
300+ * It expects that the result set contains all column mapped in the target class,
301+ * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
288302 *
289303 * @param resultSet the {@code ResultSet} to map.
290304 * @return the mapped result set. Note that the returned mapped result set
291305 * will encapsulate {@code resultSet} and so consuming results from this
292306 * returned mapped result set will consume results from {@code resultSet}
293307 * and vice-versa.
308+ *
309+ * @see #mapAliased(ResultSet)
294310 */
295311 public Result<T> map(ResultSet resultSet) {
296312 return new Result<T>(resultSet, mapper, protocolVersion);
297313 }
298314
315+ /**
316+ * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
317+ * <p>
318+ * Use this method to map a result set coming from the execution of the {@code Statement} returned by
319+ * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
320+ *
321+ * @param resultSet the {@code ResultSet} to map.
322+ * @return the mapped result set. Note that the returned mapped result set
323+ * will encapsulate {@code resultSet} and so consuming results from this
324+ * returned mapped result set will consume results from {@code resultSet}
325+ * and vice-versa.
326+ *
327+ * @see #map(ResultSet)
328+ */
329+ public Result<T> mapAliased(ResultSet resultSet) {
330+ return new Result<T>(resultSet, mapper, protocolVersion, true);
331+ }
332+
299333 /**
300334 * Creates a query to fetch entity given its PRIMARY KEY.
301335 * <p>
@@ -348,7 +382,7 @@
348382 * at least one of those values is {@code null}.
349383 */
350384 public T get(Object... primaryKey) {
351- return map(session().execute(getQuery(primaryKey))).one();
385+ return mapAliased(session().execute(getQuery(primaryKey))).one();
352386 }
353387
354388 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +2 −2
@@ -142,8 +142,8 @@
142142 return future;
143143
144144 return mapOne
145- ? Futures.transform(future, returnMapper.mapOneFunction)
146- : Futures.transform(future, returnMapper.mapAllFunction);
145+ ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
146+ : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
147147 } else {
148148 ResultSet rs = session.execute(bs);
149149 if (returnMapper == null)
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +23 −5
@@ -15,7 +15,8 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
18+import java.util.ArrayList;
19+import java.util.List;
1920
2021 import com.google.common.base.Objects;
2122
@@ -23,6 +24,7 @@
2324 import com.datastax.driver.core.querybuilder.Delete;
2425 import com.datastax.driver.core.querybuilder.Insert;
2526 import com.datastax.driver.core.querybuilder.Select;
27+
2628 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2729
2830 class QueryType {
@@ -64,14 +66,30 @@
6466 ? insertInto(mapper.getKeyspace(), mapper.getTable())
6567 : insertInto(table);
6668 for (ColumnMapper<?> cm : mapper.allColumns())
67- insert.value(cm.getColumnName(), bindMarker());
69+ if (cm.kind != ColumnMapper.Kind.COMPUTED)
70+ insert.value(cm.getColumnName(), bindMarker());
6871 return insert.toString();
6972 }
7073 case GET:
7174 {
72- Select select = table == null
73- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
74- : select().all().from(table);
75+ Select.Selection selection = select();
76+ for (ColumnMapper cm : mapper.allColumns()) {
77+ Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
78+ ? 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());
90+ } else {
91+ select = selection.from(table);
92+ }
7593 Select.Where where = select.where();
7694 for (int i = 0; i < mapper.primaryKeySize(); i++)
7795 where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +18 −16
@@ -22,8 +22,10 @@
2222 import java.lang.reflect.Type;
2323 import java.lang.reflect.Method;
2424 import java.util.*;
25+import java.util.concurrent.atomic.AtomicInteger;
2526
2627 import com.datastax.driver.core.*;
28+import com.datastax.driver.mapping.annotations.Computed;
2729
2830 /**
2931 * An {@link EntityMapper} implementation that use reflection to read and write fields
@@ -55,12 +57,12 @@
5557 private final Method readMethod;
5658 private final Method writeMethod;
5759
58- private LiteralMapper(Field field, int position, PropertyDescriptor pd) {
59- this(field, extractSimpleType(field), position, pd);
60+ private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnNumber) {
61+ this(field, extractSimpleType(field), position, pd, columnNumber);
6062 }
6163
62- private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd) {
63- super(field, type, position);
64+ private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
65+ super(field, type, position, columnCounter);
6466 this.readMethod = pd.getReadMethod();
6567 this.writeMethod = pd.getWriteMethod();
6668 }
@@ -93,8 +95,8 @@
9395 private final EnumType enumType;
9496 private final Map<String, Object> fromString;
9597
96- private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType) {
97- super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd);
98+ private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
99+ super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd, columnCounter);
98100 this.enumType = enumType;
99101
100102 if (enumType == EnumType.STRING) {
@@ -138,8 +140,8 @@
138140 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
139141 private final UDTMapper<U> udtMapper;
140142
141- private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper) {
142- super(field, udtMapper.getUserType(), position, pd);
143+ private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper, AtomicInteger columnCounter) {
144+ super(field, udtMapper.getUserType(), position, pd, columnCounter);
143145 this.udtMapper = udtMapper;
144146 }
145147
@@ -163,8 +165,8 @@
163165 private static class NestedUDTMapper<T> extends LiteralMapper<T> {
164166 private final InferredCQLType inferredCQLType;
165167
166- public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType) {
167- super(field, inferredCQLType.dataType, position, pd);
168+ public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType, AtomicInteger columnCounter) {
169+ super(field, inferredCQLType.dataType, position, pd, columnCounter);
168170 this.inferredCQLType = inferredCQLType;
169171 }
170172
@@ -199,32 +201,32 @@
199201 }
200202
201203 @SuppressWarnings({ "unchecked", "rawtypes" })
202- public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager) {
204+ public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
203205 String fieldName = field.getName();
204206 try {
205207 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
206208
207209 if (field.getType().isEnum()) {
208- return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field));
210+ return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
209211 }
210212
211213 if (TypeMappings.isMappedUDT(field.getType())) {
212214 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
213- return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper);
215+ return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper, columnCounter);
214216 }
215217
216218 if (field.getGenericType() instanceof ParameterizedType) {
217219 InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
218220 if (inferredCQLType.containsMappedUDT) {
219221 // We need a specialized mapper to convert UDT instances in the hierarchy.
220- return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType);
222+ return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType, columnCounter);
221223 } else {
222224 // The default codecs will know how to handle the extracted datatype.
223- return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd);
225+ return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd, columnCounter);
224226 }
225227 }
226228
227- return new LiteralMapper<T>(field, position, pd);
229+ return new LiteralMapper<T>(field, position, pd, columnCounter);
228230
229231 } catch (IntrospectionException e) {
230232 throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +9 −1
@@ -28,17 +28,25 @@
2828 private final ResultSet rs;
2929 private final EntityMapper<T> mapper;
3030 private final ProtocolVersion protocolVersion;
31+ private final boolean useAlias;
3132
3233 Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion) {
34+ this(rs, mapper, protocolVersion, false);
35+ }
36+
37+ Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion, boolean useAlias) {
3338 this.rs = rs;
3439 this.mapper = mapper;
3540 this.protocolVersion = protocolVersion;
41+ this.useAlias = useAlias;
3642 }
3743
3844 private T map(Row row) {
3945 T entity = mapper.newEntity();
4046 for (ColumnMapper<T> cm : mapper.allColumns()) {
41- ByteBuffer bytes = row.getBytesUnsafe(cm.getColumnName());
47+ if (!useAlias && cm.kind == ColumnMapper.Kind.COMPUTED)
48+ continue;
49+ ByteBuffer bytes = row.getBytesUnsafe(cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName());
4250 if (bytes != null)
4351 cm.setValue(entity, cm.getDataType().deserialize(bytes, protocolVersion));
4452 }
added driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +50 −0
@@ -0,0 +1,50 @@
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.annotations;
17+
18+
19+import java.lang.annotation.ElementType;
20+import com.datastax.driver.mapping.Mapper;
21+import java.lang.annotation.Retention;
22+import java.lang.annotation.RetentionPolicy;
23+import java.lang.annotation.Target;
24+
25+/**
26+ * Annotates a "computed" field, which gets filled from a CQL expression in the SELECT query
27+ * used to retrieve an entity.
28+ * <p>
29+ * Note that such fields are only filled by default mapper operations ({@link Mapper#get(Object...)}),
30+ * they will be ignored in accessor queries and save operations.
31+ * <p>
32+ * As opposed to other mapper annotation, this one doesn't handle case sensitivity. If your expression
33+ * contains case-sensitive names, you'll need to quote them explicitly:
34+ * <pre>
35+ * {@code @Computed("\"caseSensitiveFunction\"(v)")}
36+ * </pre>
37+ */
38+@Target(ElementType.FIELD)
39+@Retention(RetentionPolicy.RUNTIME)
40+public @interface Computed {
41+ /**
42+ * The formula used to compute the field.
43+ * <p>
44+ * This is a CQL expression like you would use directly in a query, for instance
45+ * "writetime(v)".
46+ *
47+ * @return the formula.
48+ */
49+ String formula();
50+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +318 −0
@@ -0,0 +1,318 @@
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.fail;
25+
26+import com.datastax.driver.core.*;
27+import com.datastax.driver.core.exceptions.InvalidQueryException;
28+import com.datastax.driver.mapping.annotations.*;
29+
30+import static com.datastax.driver.core.Assertions.assertThat;
31+
32+/**
33+ * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed}
34+ * annotation to map computed fields.
35+ */
36+@SuppressWarnings("unused")
37+public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
38+
39+ @Override
40+ protected Collection<String> getTableDefinitions() {
41+ return Lists.newArrayList(
42+ "CREATE TABLE user (login text primary key, name text)",
43+ "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
44+ }
45+
46+ MappingManager mappingManager;
47+ Mapper<User> userMapper;
48+
49+ @BeforeMethod(groups = "short")
50+ void setup() {
51+ mappingManager = new MappingManager(session);
52+ userMapper = mappingManager.mapper(User.class);
53+ }
54+
55+ @Test(groups = "short")
56+ void should_save_and_get_entity_with_computed_fields() {
57+ long writeTime = System.currentTimeMillis() * 1000;
58+ User newUser = new User("testlogin2", "blah");
59+ newUser.setWriteTime(1); // will be ignored
60+
61+ userMapper.save(newUser);
62+
63+ User fetched = userMapper.get("testlogin2");
64+ assertThat(fetched.getLogin()).isEqualTo("testlogin2");
65+ assertThat(fetched.getName()).isEqualTo("blah");
66+ // write time should be within 30 seconds.
67+ assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
68+ assertThat(fetched.getTtl()).isNull(); // TTL should be null since it was not set.
69+
70+ // Overwrite with TTL
71+ session.execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
72+ fetched = userMapper.get("testlogin2");
73+ assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
74+ assertThat(fetched.getTtl()).isBetween(570, 600); // TTL should be within 30 secs.
75+
76+ // cleanup
77+ userMapper.delete(newUser);
78+ }
79+
80+ @Test(groups = "short")
81+ void should_add_aliases_for_fields_in_select_queries() {
82+ BoundStatement bs = (BoundStatement)userMapper.getQuery("test");
83+ assertThat(bs.preparedStatement().getQueryString())
84+ .contains("SELECT", "\"login\" AS col1", "\"name\" AS col2", "writetime(\"name\") AS col3");
85+ }
86+
87+ @Test(groups = "short")
88+ public void should_map_aliased_resultset_to_objects() {
89+ Statement getQuery = userMapper.getQuery("testlogin");
90+ getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
91+ ResultSet rs = session.execute(getQuery);
92+
93+ Result<User> result = userMapper.mapAliased(rs);
94+ User user = result.one();
95+
96+ assertThat(user.getLogin()).isEqualTo("testlogin");
97+ }
98+
99+ @Test(groups = "short")
100+ void should_map_unaliased_resultset_to_objects() {
101+ UserAccessor userAccessor = mappingManager.createAccessor(UserAccessor.class);
102+ ResultSet rs = userAccessor.all();
103+
104+ Result<User> result = userMapper.map(rs);
105+ User user = result.one();
106+ assertThat(user.getLogin()).isEqualTo("testlogin");
107+ assertThat(user.getWriteTime()).isEqualTo(0);
108+ }
109+
110+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
111+ void should_fail_if_computed_field_is_not_right_type() {
112+ mappingManager.mapper(User_WrongComputedType.class);
113+ }
114+
115+ @Test(groups = "short")
116+ void should_fail_if_computed_field_marked_with_column_annotation() {
117+ Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
118+ try {
119+ mapper.save(new User_WrongAnnotationForComputed("test", "foo"));
120+ fail("Expected an InvalidQueryException");
121+ } catch (InvalidQueryException e) {/*expected*/}
122+
123+ try {
124+ User_WrongAnnotationForComputed saved = mapper.get(42);
125+ fail("Expected an InvalidQueryException");
126+ } catch (InvalidQueryException e) {/*expected*/}
127+ }
128+
129+ @Table(name = "user")
130+ public static class User {
131+ @PartitionKey
132+ private String login;
133+ private String name;
134+
135+ public User() {
136+ }
137+
138+ public User(String login, String name) {
139+ this.login = login;
140+ this.name = name;
141+ }
142+
143+ // quotes in the column name inserted on purpose
144+ // to test the alias generation mechanism
145+ @Computed(formula = "writetime(\"name\")")
146+ long writeTime;
147+
148+ @Computed(formula = "ttl(name)")
149+ Integer ttl;
150+
151+ public String getLogin() {
152+ return login;
153+ }
154+
155+ public void setLogin(String login) {
156+ this.login = login;
157+ }
158+
159+ public String getName() {
160+ return name;
161+ }
162+
163+ public void setName(String name) {
164+ this.name = name;
165+ }
166+
167+ public long getWriteTime() {
168+ return writeTime;
169+ }
170+
171+ public void setWriteTime(long writeTime) {
172+ this.writeTime = writeTime;
173+ }
174+
175+ public Integer getTtl() {
176+ return ttl;
177+ }
178+
179+ public void setTtl(Integer ttl) {
180+ this.ttl = ttl;
181+ }
182+ }
183+
184+ @Accessor
185+ interface UserAccessor {
186+ @Query("select * from user")
187+ ResultSet all();
188+ }
189+
190+ @Table(name = "key_value")
191+ public static class KeyValue {
192+ @PartitionKey
193+ private int key;
194+ private String v;
195+
196+ @Computed(formula = "writetime(\"v\")")
197+ long writeTime;
198+
199+ @Computed(formula = "ttl(v)")
200+ Integer ttl;
201+
202+ public KeyValue() {
203+ }
204+
205+ public KeyValue(int k, String val) {
206+ this.key = k;
207+ this.v = val;
208+ }
209+
210+ public int getKey() {
211+ return this.key;
212+ }
213+
214+ public void setKey(int pk) {
215+ this.key = pk;
216+ }
217+
218+ public String getV() {
219+ return this.v;
220+ }
221+
222+ public void setV(String val) {
223+ this.v = val;
224+ }
225+
226+ public long getWriteTime() {
227+ return this.writeTime;
228+ }
229+
230+ public void setWriteTime(long pk) {
231+ this.writeTime = pk;
232+ }
233+
234+ public Integer getTtl() {
235+ return this.ttl;
236+ }
237+
238+ public void setTtl(Integer ttl) {
239+ this.ttl = ttl;
240+ }
241+ }
242+
243+ @Table(name = "user")
244+ public static class User_WrongComputedType {
245+ @PartitionKey
246+ private String login;
247+ private String name;
248+
249+ @Column(name = "writetime(v)")
250+ byte writeTime;
251+
252+ public String getLogin() {
253+ return login;
254+ }
255+
256+ public void setLogin(String login) {
257+ this.login = login;
258+ }
259+
260+ public String getName() {
261+ return name;
262+ }
263+
264+ public void setName(String name) {
265+ this.name = name;
266+ }
267+
268+ public byte getWriteTime() {
269+ return writeTime;
270+ }
271+
272+ public void setWriteTime(byte writeTime) {
273+ this.writeTime = writeTime;
274+ }
275+ }
276+
277+ @Table(name = "user")
278+ public static class User_WrongAnnotationForComputed {
279+ @PartitionKey
280+ private String login;
281+ private String name;
282+
283+ @Column(name = "writetime(v)")
284+ long writeTime;
285+
286+ public User_WrongAnnotationForComputed() {
287+ }
288+
289+ public User_WrongAnnotationForComputed(String login, String name) {
290+ this.login = login;
291+ this.name = name;
292+ }
293+
294+ public String getLogin() {
295+ return login;
296+ }
297+
298+ public void setLogin(String login) {
299+ this.login = login;
300+ }
301+
302+ public String getName() {
303+ return name;
304+ }
305+
306+ public void setName(String name) {
307+ this.name = name;
308+ }
309+
310+ public long getWriteTime() {
311+ return writeTime;
312+ }
313+
314+ public void setWriteTime(long writeTime) {
315+ this.writeTime = writeTime;
316+ }
317+ }
318+}
added driver-mapping/src/test/resources/log4j.properties +28 −0
@@ -0,0 +1,28 @@
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+
17+# Set root logger level to DEBUG and its only appender to A1.
18+log4j.rootLogger=INFO, A1
19+
20+# Scassandra's info log is a bit verbose
21+log4j.logger.org.scassandra=WARN
22+
23+# A1 is set to be a ConsoleAppender.
24+log4j.appender.A1=org.apache.log4j.ConsoleAppender
25+
26+# A1 uses PatternLayout.
27+log4j.appender.A1.layout=org.apache.log4j.PatternLayout
28+log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n