Elffuss BraidHub

kikocis/java-driver public

JAVA-879: Mapper.map() accepts mapper-generated and user queries.

(cherry picked from 2.1)
Changesetb866be19c964d7a81c9c72a06e66976a87cf801acfb7704a6dc10abeeb6036a6
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 18:06 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-03-31 19:45 +02:00
Parents489fb8c56d5a

Browse the files at this changeset

13 files changed

modified changelog/README.md +1 −0
@@ -10,6 +10,7 @@
1010 - [improvement] JAVA-979: Update javadoc for RegularStatement toString() and getQueryString() to indicate that consistency level and other parameters are not maintained in the query string.
1111 - [bug] JAVA-1068: Unwrap StatementWrappers when hashing the paging state.
1212 - [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name.
13+- [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries.
1314
1415
1516 ### 3.0.0
modified clirr-ignores.xml +7 −0
@@ -9,4 +9,11 @@
99 * add new differences if needed. Difference types are explained at http://www.mojohaus.org/clirr-maven-plugin/examples/ignored-differences.html
1010 -->
1111 <differences>
12+
13+ <difference>
14+ <differenceType>1001</differenceType> <!-- decreased visibility -->
15+ <className>com/datastax/driver/mapping/ColumnMapper$Kind</className>
16+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
17+ </difference>
18+
1219 </differences>
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +18 −15
@@ -55,11 +55,8 @@
5555 }
5656
5757 static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) {
58- info = update(info, msg, session);
5958
6059 switch (msg.kind) {
61- case VOID:
62- return empty(info);
6360 case ROWS:
6461 Responses.Result.Rows r = (Responses.Result.Rows) msg;
6562
@@ -75,33 +72,40 @@
7572 Token.Factory tokenFactory = (session == null) ? null
7673 : session.getCluster().manager.metadata.tokenFactory();
7774
75+ info = update(info, r, session, r.metadata.pagingState, protocolVersion, columnDefs.codecRegistry, statement);
76+
7877 // info can be null only for internal calls, but we don't page those. We assert
79- // this explicitly because MultiPage implementation don't support info == null.
78+ // this explicitly because MultiPage implementation doesn't support info == null.
8079 assert r.metadata.pagingState == null || info != null;
8180
8281 return r.metadata.pagingState == null
8382 ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info)
84- : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement);
83+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session);
8584
85+ case VOID:
8686 case SET_KEYSPACE:
8787 case SCHEMA_CHANGE:
88+ info = update(info, msg, session, null, protocolVersion, null, statement);
8889 return empty(info);
8990 case PREPARED:
9091 throw new RuntimeException("Prepared statement received when a ResultSet was expected");
9192 default:
9293 logger.error("Received unknown result type '{}'; returning empty result set", msg.kind);
94+ info = update(info, msg, session, null, protocolVersion, null, statement);
9395 return empty(info);
9496 }
9597 }
9698
97- private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session) {
99+ private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session,
100+ ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry,
101+ Statement statement) {
98102 if (info == null)
99103 return null;
100104
101105 UUID tracingId = msg.getTracingId();
102106 QueryTrace trace = (tracingId == null) ? null : new QueryTrace(tracingId, session);
103107
104- return info.withTraceAndWarnings(trace, msg.warnings);
108+ return info.with(trace, msg.warnings, pagingState, statement, protocolVersion, codecRegistry);
105109 }
106110
107111 private static ArrayBackedResultSet empty(ExecutionInfo info) {
@@ -236,7 +240,6 @@
236240 private volatile FetchingState fetchState;
237241
238242 private final SessionManager session;
239- private final Statement statement;
240243
241244 private MultiPage(ColumnDefinitions metadata,
242245 Token.Factory tokenFactory,
@@ -245,19 +248,17 @@
245248 Queue<List<ByteBuffer>> rows,
246249 ExecutionInfo info,
247250 ByteBuffer pagingState,
248- SessionManager session,
249- Statement statement) {
251+ SessionManager session) {
250252
251253 // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so
252254 // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure
253255 // that this will never change, so apply the generic check by peeking at the first row.
254256 super(metadata, tokenFactory, rows.peek(), protocolVersion, codecRegistry);
255257 this.currentPage = rows;
256- this.infos.offer(info.withPagingState(pagingState, protocolVersion, codecRegistry).withStatement(statement));
258+ this.infos.offer(info);
257259
258260 this.fetchState = new FetchingState(pagingState, null);
259261 this.session = session;
260- this.statement = statement;
261262 }
262263
263264 @Override
@@ -331,6 +332,9 @@
331332
332333 private ListenableFuture<ResultSet> queryNextPage(ByteBuffer nextStart, final SettableFuture<ResultSet> future) {
333334
335+ Statement statement = this.infos.peek().getStatement();
336+
337+
334338 assert !(statement instanceof BatchStatement);
335339
336340 final Message.Request request = session.makeRequestMessage(statement, nextStart);
@@ -351,15 +355,14 @@
351355 switch (response.type) {
352356 case RESULT:
353357 Responses.Result rm = (Responses.Result) response;
354- info = update(info, rm, MultiPage.this.session);
355358 if (rm.kind == Responses.Result.Kind.ROWS) {
356359 Responses.Result.Rows rows = (Responses.Result.Rows) rm;
357- if (rows.metadata.pagingState != null)
358- info = info.withPagingState(rows.metadata.pagingState, protocolVersion, codecRegistry).withStatement(statement);
360+ info = update(info, rm, MultiPage.this.session, rows.metadata.pagingState, protocolVersion, codecRegistry, statement);
359361 MultiPage.this.nextPages.offer(rows.data);
360362 MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null);
361363 } else if (rm.kind == Responses.Result.Kind.VOID) {
362364 // We shouldn't really get a VOID message here but well, no harm in handling it I suppose
365+ info = update(info, rm, MultiPage.this.session, null, protocolVersion, codecRegistry, statement);
363366 MultiPage.this.fetchState = null;
364367 } else {
365368 logger.error("Received unknown result type '{}' during paging: ignoring message", rm.kind);
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +17 −10
@@ -56,20 +56,19 @@
5656 this(triedHosts, null, null, null, null, null, null, true, Collections.<String>emptyList(), null);
5757 }
5858
59- ExecutionInfo withTraceAndWarnings(QueryTrace newTrace, List<String> warnings) {
60- return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
61- }
62-
6359 ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) {
6460 return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
6561 }
6662
67- ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
68- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
69- }
70-
71- ExecutionInfo withStatement(Statement statement) {
72- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload);
63+ ExecutionInfo with(QueryTrace newTrace, List<String> newWarnings, ByteBuffer newPagingState, Statement newStatement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
64+ return new ExecutionInfo(this.triedHosts, this.achievedConsistency,
65+ newTrace,
66+ newPagingState, protocolVersion, codecRegistry,
67+ newStatement,
68+ schemaInAgreement,
69+ newWarnings,
70+ incomingPayload
71+ );
7372 }
7473
7574 ExecutionInfo withIncomingPayload(Map<String, ByteBuffer> incomingPayload) {
@@ -251,4 +250,12 @@
251250 return incomingPayload;
252251 }
253252
253+ /**
254+ * Get the statement that has been executed.
255+ *
256+ * @return the statement executed.
257+ */
258+ public Statement getStatement() {
259+ return this.statement;
260+ }
254261 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +5 −7
@@ -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;
@@ -52,17 +50,17 @@
5250 this.customCodec = AnnotationParser.customCodec(field);
5351 }
5452
55- public abstract Object getValue(T entity);
53+ abstract Object getValue(T entity);
5654
57- public abstract void setValue(T entity, Object value);
55+ abstract void setValue(T entity, Object value);
5856
59- public String getColumnName() {
57+ String getColumnName() {
6058 return kind == Kind.COMPUTED
6159 ? columnName
6260 : Metadata.quote(columnName);
6361 }
6462
65- public String getAlias() {
63+ String getAlias() {
6664 return alias;
6765 }
6866
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>() {
@@ -330,7 +329,7 @@
330329 if (primaryKeys.size() != mapper.primaryKeySize())
331330 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
332331
333- BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
332+ BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options));
334333 int i = 0;
335334 for (Object value : primaryKeys) {
336335 ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
@@ -367,7 +366,7 @@
367366 * at least one of those values is {@code null}.
368367 */
369368 public T get(Object... objects) {
370- return mapAliased(session().execute(getQuery(objects))).one();
369+ return map(session().execute(getQuery(objects))).one();
371370 }
372371
373372 /**
@@ -610,39 +609,37 @@
610609 /**
611610 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
612611 * <p/>
613- * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
614- * manual query or an {@link Accessor method}.
615- * It expects that the result set contains all column mapped in the target class,
616- * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
612+ * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with
613+ * {@link com.datastax.driver.mapping.annotations.Query @Query} in an
614+ * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns
615+ * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be
616+ * populated.
617+ * <p/>
618+ * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be
619+ * mapped, as if the object came from a direct {@link #get(Object...)} call.
617620 *
618621 * @param resultSet the {@code ResultSet} to map.
619622 * @return the mapped result set. Note that the returned mapped result set
620623 * will encapsulate {@code resultSet} and so consuming results from this
621624 * returned mapped result set will consume results from {@code resultSet}
622625 * and vice-versa.
623- * @see #mapAliased(ResultSet)
624626 */
625627 public Result<T> map(ResultSet resultSet) {
626- return new Result<T>(resultSet, mapper, protocolVersion);
628+ boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet);
629+ return new Result<T>(resultSet, mapper, protocolVersion, useAlias);
630+ }
631+
632+ private boolean isFromMapperQuery(ResultSet resultSet) {
633+ return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement;
627634 }
628635
629636 /**
630- * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
631- * <p/>
632- * Use this method to map a result set coming from the execution of the {@code Statement} returned by
633- * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
634- *
635- * @param resultSet the {@code ResultSet} to map.
636- * @return the mapped result set. Note that the returned mapped result set
637- * will encapsulate {@code resultSet} and so consuming results from this
638- * returned mapped result set will consume results from {@code resultSet}
639- * and vice-versa.
640- * @see #map(ResultSet)
637+ * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use
638+ * {@link #map(ResultSet)} instead of this method.
641639 */
640+ @Deprecated
642641 public Result<T> mapAliased(ResultSet resultSet) {
643- return (manager.isCassandraV1)
644- ? map(resultSet) // no aliases
645- : new Result<T>(resultSet, mapper, protocolVersion, true);
642+ return map(resultSet);
646643 }
647644
648645 /**
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 +2 −2
@@ -60,7 +60,7 @@
6060 }
6161
6262 @Override
63- public Object getValue(T entity) {
63+ Object getValue(T entity) {
6464 try {
6565 return readMethod.invoke(entity);
6666 } catch (IllegalArgumentException e) {
@@ -71,7 +71,7 @@
7171 }
7272
7373 @Override
74- public void setValue(Object entity, Object value) {
74+ void setValue(Object entity, Object value) {
7575 try {
7676 writeMethod.invoke(entity, value);
7777 } catch (IllegalArgumentException e) {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +1 −5
@@ -29,10 +29,6 @@
2929 private final ProtocolVersion protocolVersion;
3030 private final boolean useAlias;
3131
32- Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion) {
33- this(rs, mapper, protocolVersion, false);
34- }
35-
3632 Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion, boolean useAlias) {
3733 this.rs = rs;
3834 this.mapper = mapper;
@@ -120,7 +116,7 @@
120116 * this mapped result set.
121117 */
122118 @Override
123- public Iterator<T> iterator() {
119+ public Iterator<T> iterator() {
124120 return new Iterator<T>() {
125121 private final Iterator<Row> rowIterator = rs.iterator();
126122
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +1 −1
@@ -103,7 +103,7 @@
103103 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
104104 ResultSet rs = session().execute(getQuery);
105105
106- Result<User> result = userMapper.mapAliased(rs);
106+ Result<User> result = userMapper.map(rs);
107107 User user = result.one();
108108
109109 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
@@ -145,17 +145,18 @@
145145 @Table(name = "posts")
146146 public static class Post {
147147
148- @PartitionKey
149- @Column(name = "user_id")
150- private UUID userId;
148+ private String title;
149+ private String content;
150+ private InetAddress device;
151151
152152 @ClusteringColumn
153153 @Column(name = "post_id")
154154 private UUID postId;
155155
156- private String title;
157- private String content;
158- private InetAddress device;
156+ @PartitionKey
157+ @Column(name = "user_id")
158+ private UUID userId;
159+
159160
160161 private Set<String> tags;
161162
@@ -395,7 +396,6 @@
395396 session().execute("delete from posts where user_id = " + u1.getUserId());
396397 }
397398
398-
399399 @Test(groups = "short")
400400 public void should_return_table_metadata() throws Exception {
401401 MappingManager manager = new MappingManager(session());