Elffuss BraidHub

kikocis/java-driver public

Merge pull request #608 from datastax/java879

JAVA-879: Mapper.map() accepts mapper-generated and user queries.
Changeset0d80a592348825bab6d4398b88c11f6a58b5be910cf6d46d192ee5669de80f05
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 18:06 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 18:06 +01:00
Parentsdc23ffd69e7e, 01e81a53fd78

Browse the files at this changeset

13 files changed

modified changelog/README.md +1 −0
@@ -21,6 +21,7 @@
2121 - [bug] JAVA-1068: Unwrap StatementWrappers when hashing the paging state.
2222 - [bug] JAVA-831: Mapper can't load an entity where the PK is a UDT.
2323 - [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name.
24+- [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries.
2425
2526 Merged from 2.0 branch:
2627
modified clirr-ignores.xml +7 −1
@@ -46,5 +46,11 @@
4646 <className>com/datastax/driver/core/ConvictionPolicy$Simple$Factory</className>
4747 <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
4848 </difference>
49-
49+
50+ <difference>
51+ <differenceType>1001</differenceType> <!-- decreased visibility -->
52+ <className>com/datastax/driver/mapping/ColumnMapper$Kind</className>
53+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
54+ </difference>
55+
5056 </differences>
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +22 −15
@@ -52,11 +52,8 @@
5252 }
5353
5454 static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) {
55- info = update(info, msg, session);
5655
5756 switch (msg.kind) {
58- case VOID:
59- return empty(info);
6057 case ROWS:
6158 Responses.Result.Rows r = (Responses.Result.Rows) msg;
6259
@@ -72,27 +69,38 @@
7269 Token.Factory tokenFactory = (session == null) ? null
7370 : session.getCluster().manager.metadata.tokenFactory();
7471
72+ info = update(info, r, session, r.metadata.pagingState, protocolVersion, statement);
73+
7574 // info can be null only for internal calls, but we don't page those. We assert
76- // this explicitly because MultiPage implementation don't support info == null.
75+ // this explicitly because MultiPage implementation doesn't support info == null.
7776 assert r.metadata.pagingState == null || info != null;
7877 return r.metadata.pagingState == null
7978 ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
80- : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
79+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session);
8180
81+ case VOID:
8282 case SET_KEYSPACE:
8383 case SCHEMA_CHANGE:
84+ info = update(info, msg, session, null, protocolVersion, statement);
8485 return empty(info);
8586 case PREPARED:
8687 throw new RuntimeException("Prepared statement received when a ResultSet was expected");
8788 default:
8889 logger.error("Received unknown result type '{}'; returning empty result set", msg.kind);
90+ info = update(info, msg, session, null, protocolVersion, statement);
8991 return empty(info);
9092 }
9193 }
9294
93- private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session) {
95+ private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session,
96+ ByteBuffer pagingState, ProtocolVersion protocolVersion, Statement statement) {
97+ if (info == null)
98+ return null;
99+
94100 UUID tracingId = msg.getTracingId();
95- return tracingId == null || info == null ? info : info.withTrace(new QueryTrace(tracingId, session));
101+ QueryTrace trace = (tracingId == null) ? null : new QueryTrace(tracingId, session);
102+
103+ return info.with(trace, pagingState, statement, protocolVersion);
96104 }
97105
98106 private static ArrayBackedResultSet empty(ExecutionInfo info) {
@@ -226,7 +234,6 @@
226234 private volatile FetchingState fetchState;
227235
228236 private final SessionManager session;
229- private final Statement statement;
230237
231238 private MultiPage(ColumnDefinitions metadata,
232239 Token.Factory tokenFactory,
@@ -234,19 +241,17 @@
234241 Queue<List<ByteBuffer>> rows,
235242 ExecutionInfo info,
236243 ByteBuffer pagingState,
237- SessionManager session,
238- Statement statement) {
244+ SessionManager session) {
239245
240246 // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so
241247 // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure
242248 // that this will never change, so apply the generic check by peeking at the first row.
243249 super(metadata, tokenFactory, rows.peek(), protocolVersion);
244250 this.currentPage = rows;
245- this.infos.offer(info.withPagingState(pagingState, protocolVersion).withStatement(statement));
251+ this.infos.offer(info);
246252
247253 this.fetchState = new FetchingState(pagingState, null);
248254 this.session = session;
249- this.statement = statement;
250255 }
251256
252257 @Override
@@ -320,6 +325,9 @@
320325
321326 private ListenableFuture<Void> queryNextPage(ByteBuffer nextStart, final SettableFuture<Void> future) {
322327
328+ Statement statement = this.infos.peek().getStatement();
329+
330+
323331 assert !(statement instanceof BatchStatement);
324332
325333 final Message.Request request = session.makeRequestMessage(statement, nextStart);
@@ -340,15 +348,14 @@
340348 switch (response.type) {
341349 case RESULT:
342350 Responses.Result rm = (Responses.Result) response;
343- info = update(info, rm, MultiPage.this.session);
344351 if (rm.kind == Responses.Result.Kind.ROWS) {
345352 Responses.Result.Rows rows = (Responses.Result.Rows) rm;
346- if (rows.metadata.pagingState != null)
347- info = info.withPagingState(rows.metadata.pagingState, protocolVersion).withStatement(statement);
353+ info = update(info, rm, MultiPage.this.session, rows.metadata.pagingState, protocolVersion, statement);
348354 MultiPage.this.nextPages.offer(rows.data);
349355 MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null);
350356 } else if (rm.kind == Responses.Result.Kind.VOID) {
351357 // We shouldn't really get a VOID message here but well, no harm in handling it I suppose
358+ info = update(info, rm, MultiPage.this.session, null, protocolVersion, statement);
352359 MultiPage.this.fetchState = null;
353360 } else {
354361 logger.error("Received unknown result type '{}' during paging: ignoring message", rm.kind);
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +16 −10
@@ -46,20 +46,17 @@
4646 this(triedHosts, null, null, null, null, null, true);
4747 }
4848
49- ExecutionInfo withTrace(QueryTrace newTrace) {
50- return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, statement, schemaInAgreement);
51- }
52-
5349 ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) {
5450 return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
5551 }
5652
57- ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion) {
58- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
59- }
60-
61- ExecutionInfo withStatement(Statement statement) {
62- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, statement, schemaInAgreement);
53+ ExecutionInfo with(QueryTrace newTrace, ByteBuffer newPagingState, Statement newStatement, ProtocolVersion protocolVersion) {
54+ return new ExecutionInfo(this.triedHosts, this.achievedConsistency,
55+ newTrace,
56+ newPagingState, protocolVersion,
57+ newStatement,
58+ schemaInAgreement
59+ );
6360 }
6461
6562 /**
@@ -185,4 +182,13 @@
185182 void setSchemaInAgreement(boolean schemaAgreement) {
186183 this.schemaInAgreement = schemaAgreement;
187184 }
185+
186+ /**
187+ * Get the statement that has been executed.
188+ *
189+ * @return the statement executed.
190+ */
191+ public Statement getStatement() {
192+ return this.statement;
193+ }
188194 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +6 −8
@@ -24,9 +24,7 @@
2424
2525 abstract class ColumnMapper<T> {
2626
27- public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED}
28-
29- ;
27+ enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED}
3028
3129 private final String columnName;
3230 private final String alias;
@@ -51,21 +49,21 @@
5149 this.position = position;
5250 }
5351
54- public abstract Object getValue(T entity);
52+ abstract Object getValue(T entity);
5553
56- public abstract void setValue(T entity, Object value);
54+ abstract void setValue(T entity, Object value);
5755
58- public String getColumnName() {
56+ String getColumnName() {
5957 return kind == Kind.COMPUTED
6058 ? columnName
6159 : quote(columnName);
6260 }
6361
64- public String getAlias() {
62+ String getAlias() {
6563 return alias;
6664 }
6765
68- public DataType getDataType() {
66+ DataType getDataType() {
6967 return dataType;
7068 }
7169
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +14 −14
@@ -26,16 +26,16 @@
2626
2727 abstract class EntityMapper<T> {
2828
29- public final Class<T> entityClass;
29+ final Class<T> entityClass;
3030 private final String keyspace;
3131 private final String table;
3232
33- public final ConsistencyLevel writeConsistency;
34- public final ConsistencyLevel readConsistency;
33+ final ConsistencyLevel writeConsistency;
34+ final ConsistencyLevel readConsistency;
3535
36- public final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>();
37- public final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>();
38- public final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>();
36+ final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>();
37+ final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>();
38+ final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>();
3939
4040 private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>();
4141
@@ -47,23 +47,23 @@
4747 this.readConsistency = readConsistency;
4848 }
4949
50- public String getKeyspace() {
50+ String getKeyspace() {
5151 return quote(keyspace);
5252 }
5353
54- public String getTable() {
54+ String getTable() {
5555 return quote(table);
5656 }
5757
58- public int primaryKeySize() {
58+ int primaryKeySize() {
5959 return partitionKeys.size() + clusteringColumns.size();
6060 }
6161
62- public ColumnMapper<T> getPrimaryKeyColumn(int i) {
62+ ColumnMapper<T> getPrimaryKeyColumn(int i) {
6363 return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size());
6464 }
6565
66- public void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) {
66+ void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) {
6767 partitionKeys.addAll(pks);
6868 allColumns.addAll(pks);
6969
@@ -73,14 +73,14 @@
7373 addColumns(rgs);
7474 }
7575
76- public void addColumns(List<ColumnMapper<T>> rgs) {
76+ void addColumns(List<ColumnMapper<T>> rgs) {
7777 regularColumns.addAll(rgs);
7878 allColumns.addAll(rgs);
7979 }
8080
81- public abstract T newEntity();
81+ abstract T newEntity();
8282
83- public List<ColumnMapper<T>> allColumns() {
83+ List<ColumnMapper<T>> allColumns() {
8484 return allColumns;
8585 }
8686
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +21 −24
@@ -20,7 +20,6 @@
2020 import com.datastax.driver.core.querybuilder.Insert;
2121 import com.datastax.driver.core.querybuilder.QueryBuilder;
2222 import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
23-import com.datastax.driver.mapping.annotations.Accessor;
2423 import com.datastax.driver.mapping.annotations.Computed;
2524 import com.google.common.base.Function;
2625 import com.google.common.base.Functions;
@@ -79,7 +78,7 @@
7978 this.mapOneFunction = new Function<ResultSet, T>() {
8079 @Override
8180 public T apply(ResultSet rs) {
82- return Mapper.this.mapAliased(rs).one();
81+ return Mapper.this.map(rs).one();
8382 }
8483 };
8584 this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
@@ -322,7 +321,7 @@
322321 if (primaryKeys.size() != mapper.primaryKeySize())
323322 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
324323
325- BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
324+ BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options));
326325 int i = 0;
327326 for (Object value : primaryKeys) {
328327 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
@@ -359,7 +358,7 @@
359358 * at least one of those values is {@code null}.
360359 */
361360 public T get(Object... objects) {
362- return mapAliased(session().execute(getQuery(objects))).one();
361+ return map(session().execute(getQuery(objects))).one();
363362 }
364363
365364 /**
@@ -602,39 +601,37 @@
602601 /**
603602 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
604603 * <p/>
605- * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
606- * manual query or an {@link Accessor method}.
607- * It expects that the result set contains all column mapped in the target class,
608- * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
604+ * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with
605+ * {@link com.datastax.driver.mapping.annotations.Query @Query} in an
606+ * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns
607+ * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be
608+ * populated.
609+ * <p/>
610+ * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be
611+ * mapped, as if the object came from a direct {@link #get(Object...)} call.
609612 *
610613 * @param resultSet the {@code ResultSet} to map.
611614 * @return the mapped result set. Note that the returned mapped result set
612615 * will encapsulate {@code resultSet} and so consuming results from this
613616 * returned mapped result set will consume results from {@code resultSet}
614617 * and vice-versa.
615- * @see #mapAliased(ResultSet)
616618 */
617619 public Result<T> map(ResultSet resultSet) {
618- return new Result<T>(resultSet, mapper, protocolVersion);
620+ boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet);
621+ return new Result<T>(resultSet, mapper, protocolVersion, useAlias);
622+ }
623+
624+ private boolean isFromMapperQuery(ResultSet resultSet) {
625+ return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement;
619626 }
620627
621628 /**
622- * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
623- * <p/>
624- * Use this method to map a result set coming from the execution of the {@code Statement} returned by
625- * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
626- *
627- * @param resultSet the {@code ResultSet} to map.
628- * @return the mapped result set. Note that the returned mapped result set
629- * will encapsulate {@code resultSet} and so consuming results from this
630- * returned mapped result set will consume results from {@code resultSet}
631- * and vice-versa.
632- * @see #map(ResultSet)
629+ * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use
630+ * {@link #map(ResultSet)} instead of this method.
633631 */
632+ @Deprecated
634633 public Result<T> mapAliased(ResultSet resultSet) {
635- return (manager.isCassandraV1)
636- ? map(resultSet) // no aliases
637- : new Result<T>(resultSet, mapper, protocolVersion, true);
634+ return map(resultSet);
638635 }
639636
640637 /**
added driver-mapping/src/main/java/com/datastax/driver/mapping/MapperBoundStatement.java +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+package com.datastax.driver.mapping;
17+
18+import com.datastax.driver.core.BoundStatement;
19+import com.datastax.driver.core.PreparedStatement;
20+
21+/**
22+ * A bound statement that was generated by the object mapper.
23+ */
24+class MapperBoundStatement extends BoundStatement {
25+ public MapperBoundStatement(PreparedStatement statement) {
26+ super(statement);
27+ }
28+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +4 −4
@@ -70,7 +70,7 @@
7070 }
7171
7272 @Override
73- public Object getValue(T entity) {
73+ Object getValue(T entity) {
7474 try {
7575 return toSerializableValue(readMethod.invoke(entity));
7676 } catch (IllegalArgumentException e) {
@@ -81,7 +81,7 @@
8181 }
8282
8383 @Override
84- public void setValue(Object entity, Object value) {
84+ void setValue(Object entity, Object value) {
8585 try {
8686 writeMethod.invoke(entity, value);
8787 } catch (IllegalArgumentException e) {
@@ -112,7 +112,7 @@
112112 }
113113
114114 @Override
115- public void setValue(Object entity, Object value) {
115+ void setValue(Object entity, Object value) {
116116 Object converted = null;
117117 switch (enumType) {
118118 case STRING:
@@ -147,7 +147,7 @@
147147 }
148148
149149 @Override
150- public void setValue(Object entity, Object value) {
150+ void setValue(Object entity, Object value) {
151151 assert value instanceof UDTValue;
152152 UDTValue udtValue = (UDTValue) value;
153153 assert udtValue.getType().equals(udtMapper.getUserType());
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +3 −6
@@ -35,10 +35,6 @@
3535 private final ProtocolVersion protocolVersion;
3636 private final boolean useAlias;
3737
38- Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion) {
39- this(rs, mapper, protocolVersion, false);
40- }
41-
4238 Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion, boolean useAlias) {
4339 this.rs = rs;
4440 this.mapper = mapper;
@@ -50,8 +46,9 @@
5046 T entity = mapper.newEntity();
5147 for (ColumnMapper<T> cm : mapper.allColumns()) {
5248 String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName();
53- if (!row.getColumnDefinitions().contains(name))
49+ if (!row.getColumnDefinitions().contains(name)) {
5450 continue;
51+ }
5552 ByteBuffer bytes = row.getBytesUnsafe(name);
5653 if (bytes != null)
5754 cm.setValue(entity, cm.getDataType().deserialize(bytes, protocolVersion));
@@ -108,7 +105,7 @@
108105 * this mapped result set.
109106 */
110107 @Override
111- public Iterator<T> iterator() {
108+ public Iterator<T> iterator() {
112109 return new Iterator<T>() {
113110 private final Iterator<Row> rowIterator = rs.iterator();
114111
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +1 −1
@@ -102,7 +102,7 @@
102102 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
103103 ResultSet rs = session().execute(getQuery);
104104
105- Result<User> result = userMapper.mapAliased(rs);
105+ Result<User> result = userMapper.map(rs);
106106 User user = result.one();
107107
108108 assertThat(user.getLogin()).isEqualTo("testlogin");
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +1 −1
@@ -83,7 +83,7 @@
8383
8484 ResultSet rs = session().execute(bs);
8585 assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
86- User us = mapper.mapAliased(rs).one();
86+ User us = mapper.map(rs).one();
8787 assertThat(us.getV()).isEqualTo("toget");
8888
8989 mapper.getQuery(45, Option.timestamp(1337));
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +7 −7
@@ -157,17 +157,18 @@
157157 @Table(name = "posts")
158158 public static class Post {
159159
160- @PartitionKey
161- @Column(name = "user_id")
162- private UUID userId;
160+ private String title;
161+ private String content;
162+ private InetAddress device;
163163
164164 @ClusteringColumn
165165 @Column(name = "post_id")
166166 private UUID postId;
167167
168- private String title;
169- private String content;
170- private InetAddress device;
168+ @PartitionKey
169+ @Column(name = "user_id")
170+ private UUID userId;
171+
171172
172173 private Set<String> tags;
173174
@@ -423,7 +424,6 @@
423424 session().execute("delete from posts where user_id = " + u1.getUserId());
424425 }
425426
426-
427427 @Test(groups = "short")
428428 public void should_return_table_metadata() throws Exception {
429429 MappingManager manager = new MappingManager(session());