Elffuss BraidHub

kikocis/java-driver public

Merge pull request #738 from datastax/java1272

JAVA-1272: BuiltStatement not able to print its query string if it contains mapped UDTs.
Changesetc85d930413ffcfeacd56e6cd92bb6280497667115f640e548185dc8400db2718
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-09-16 10:46 -07:00
CommitterGitHub <noreply@github.com> · 2016-09-16 10:46 -07:00
Parentsc16b0d92503b, 7a0a782b9e9f

Browse the files at this changeset

9 files changed

modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +2 −2
@@ -135,12 +135,12 @@
135135 if (statement.hasValues())
136136 throw new IllegalArgumentException("A statement to prepare should not have values");
137137
138- ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(), statement.getOutgoingPayload());
138+ final CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry();
139+ ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(codecRegistry), statement.getOutgoingPayload());
139140 return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
140141 @Override
141142 public PreparedStatement apply(PreparedStatement prepared) {
142143 ProtocolVersion protocolVersion = getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
143- CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry();
144144 ByteBuffer routingKey = statement.getRoutingKey(protocolVersion, codecRegistry);
145145 if (routingKey != null)
146146 prepared.setRoutingKey(routingKey);
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +1 −1
@@ -90,7 +90,7 @@
9090 if (statement instanceof RegularStatement) {
9191 RegularStatement st = (RegularStatement) statement;
9292 ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry);
93- String query = st.getQueryString();
93+ String query = st.getQueryString(codecRegistry);
9494 idAndVals.ids.add(query);
9595 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
9696 } else {
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +1 −1
@@ -560,7 +560,7 @@
560560 List<ByteBuffer> positionalValues = rawPositionalValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawPositionalValues);
561561 Map<String, ByteBuffer> namedValues = rawNamedValues == null ? Collections.<String, ByteBuffer>emptyMap() : rawNamedValues;
562562
563- String qString = rs.getQueryString();
563+ String qString = rs.getQueryString(codecRegistry);
564564
565565 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(Message.Request.Type.QUERY, consistency, positionalValues, namedValues,
566566 false, fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +2 −2
@@ -533,8 +533,8 @@
533533 * {@link TupleValue}, and the internal representation of a {@code ROWS} response),
534534 * which may appear in driver logs.</li>
535535 * </ol>
536- * If choose not to implement this method, you can return a constant string (for example
537- * "XxxCodec.format not implemented").
536+ * If you choose not to implement this method, you should not throw an exception but
537+ * instead return a constant string (for example "XxxCodec.format not implemented").
538538 *
539539 * @param value An instance of T; may be {@code null}.
540540 * @return CQL string
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +1 −1
@@ -66,7 +66,7 @@
6666 builder.append(maybeAddSemicolon(bst.buildQueryString(variables, codecRegistry)));
6767
6868 } else {
69- String str = stmt.getQueryString();
69+ String str = stmt.getQueryString(codecRegistry);
7070 builder.append(str);
7171 if (!str.trim().endsWith(";"))
7272 builder.append(';');
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +11 −6
@@ -292,14 +292,19 @@
292292 @Override
293293 public String toString() {
294294 try {
295- if (forceNoValues) {
295+ if (forceNoValues)
296296 return getQueryString();
297+ // 1) try first with all values inlined (will not work if some values require custom codecs,
298+ // or if the required codecs are registered in a different CodecRegistry instance than the default one)
299+ return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
300+ } catch (RuntimeException e1) {
301+ // 2) try next with bind markers for all values to avoid usage of custom codecs
302+ try {
303+ return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString();
304+ } catch (RuntimeException e2) {
305+ // Ugly but we have absolutely no context to get the registry from
306+ return String.format("built query (could not generate with default codec registry: %s)", e2.getMessage());
297307 }
298- StringBuilder queryString = buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE);
299- return maybeAddSemicolon(queryString).toString();
300- } catch (CodecNotFoundException e) {
301- // Ugly but we have absolutely no context to get the registry from
302- return String.format("built query (could not generate with default codec registry: %s)", e.getMessage());
303308 }
304309 }
305310
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +63 −9
@@ -727,16 +727,11 @@
727727 assertTrue(query.isTracing());
728728 }
729729
730- @Test(groups = "unit")
730+ @Test(groups = "unit", expectedExceptions = CodecNotFoundException.class)
731731 public void rejectUnknownValueTest() throws Exception {
732- try {
733- RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
734- .setForceNoValues(true);
735- s.getQueryString();
736- fail("should have failed to inline a byte[]");
737- } catch (CodecNotFoundException e) {
738- // Ok, that's what we expect
739- }
732+ RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
733+ .setForceNoValues(true);
734+ s.getQueryString();
740735 }
741736
742737 @Test(groups = "unit")
@@ -999,4 +994,63 @@
999994 }
1000995 }
1001996
997+ static class Foo {
998+ int bar;
999+
1000+ public Foo(int bar) {
1001+ this.bar = bar;
1002+ }
1003+ }
1004+
1005+ static class FooCodec extends TypeCodec<Foo> {
1006+
1007+ public FooCodec() {
1008+ super(DataType.cint(), Foo.class);
1009+ }
1010+
1011+ @Override
1012+ public ByteBuffer serialize(Foo value, ProtocolVersion protocolVersion) throws InvalidTypeException {
1013+ // not relevant for this test
1014+ return null;
1015+ }
1016+
1017+ @Override
1018+ public Foo deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
1019+ // not relevant for this test
1020+ return null;
1021+ }
1022+
1023+ @Override
1024+ public Foo parse(String value) throws InvalidTypeException {
1025+ // not relevant for this test
1026+ return null;
1027+ }
1028+
1029+ @Override
1030+ public String format(Foo foo) throws InvalidTypeException {
1031+ return Integer.toString(foo.bar);
1032+ }
1033+ }
1034+
1035+ /**
1036+ * Ensures that a statement can be printed with and without
1037+ * a required custom codec.
1038+ * The expectation is that if the codec is not registered,
1039+ * then the query string should contain bind markers for all variables;
1040+ * if however all codecs are properly registered, then
1041+ * the query string should contain all variables inlined and formatted properly.
1042+ *
1043+ * @jira_ticket JAVA-1272
1044+ */
1045+ @Test(groups = "unit")
1046+ public void should_inline_custom_codec() throws Exception {
1047+ assertThat(
1048+ insertInto("users").value("id", new Foo(42)).toString())
1049+ .isEqualTo("INSERT INTO users (id) VALUES (?);");
1050+ CodecRegistry.DEFAULT_INSTANCE.register(new FooCodec());
1051+ assertThat(
1052+ insertInto("users").value("id", new Foo(42)).toString())
1053+ .isEqualTo("INSERT INTO users (id) VALUES (42);");
1054+ }
1055+
10021056 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +26 −4
@@ -87,13 +87,35 @@
8787
8888 @Override
8989 protected String formatField(T source, String fieldName) {
90- // This codec implementation is internal-use only, and its format method is never used
91- throw new UnsupportedOperationException();
90+ if (!fieldName.startsWith("\""))
91+ fieldName = Metadata.quote(fieldName);
92+
93+ ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
94+
95+ if (columnMapper == null)
96+ return null;
97+
98+ Object value = columnMapper.getValue(source);
99+
100+ TypeCodec<Object> codec = columnMapper.getCustomCodec();
101+ if (codec == null)
102+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
103+
104+ return codec.format(value);
92105 }
93106
94107 @Override
95108 protected T parseAndSetField(String input, T target, String fieldName) {
96- // This codec implementation is internal-use only, and its parse method is never used
97- throw new UnsupportedOperationException();
109+ if (!fieldName.startsWith("\""))
110+ fieldName = Metadata.quote(fieldName);
111+
112+ ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
113+ if (columnMapper != null) {
114+ TypeCodec<Object> codec = columnMapper.getCustomCodec();
115+ if (codec == null)
116+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
117+ columnMapper.setValue(target, codec.parse(input));
118+ }
119+ return target;
98120 }
99121 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +45 −0
@@ -18,6 +18,7 @@
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
2020 import com.datastax.driver.core.exceptions.InvalidQueryException;
21+import com.datastax.driver.core.querybuilder.BuiltStatement;
2122 import com.datastax.driver.core.utils.CassandraVersion;
2223 import com.datastax.driver.core.utils.UUIDs;
2324 import com.datastax.driver.mapping.annotations.*;
@@ -31,6 +32,7 @@
3132 import java.util.*;
3233
3334 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3436 import static org.assertj.core.api.Assertions.assertThat;
3537 import static org.assertj.core.api.Assertions.fail;
3638 import static org.testng.Assert.*;
@@ -728,4 +730,47 @@
728730 manager.mapper(UserWithAddressUnknownField.class);
729731 }
730732
733+ /**
734+ * Ensures that MappedUDTCodec is able to properly format UDTs when printing the query string of a BuiltStatement.
735+ *
736+ * @jira_ticket JAVA-1272
737+ * @test_category object_mapper
738+ */
739+ @Test(groups = "short")
740+ public void should_format_mapped_udt() throws Exception {
741+ MappingManager manager = new MappingManager(session());
742+ UUID uuid = UUIDs.random();
743+ BuiltStatement update =
744+ update("users")
745+ .with(set("mainaddress", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")))
746+ .where(eq("user_id", uuid));
747+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
748+ codecRegistry.register(manager.udtCodec(Address.class));
749+ String queryString = update.getQueryString(codecRegistry);
750+ assertThat(queryString)
751+ .isEqualTo("UPDATE users SET mainaddress=? WHERE user_id=?;");
752+ update.setForceNoValues(true);
753+ queryString = update.getQueryString(codecRegistry);
754+ assertThat(queryString).isEqualTo(
755+ "UPDATE users " +
756+ "SET mainaddress={street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}} " +
757+ "WHERE user_id=" + uuid + ";");
758+ // check that the query string is valid
759+ session().execute(queryString);
760+ }
761+
762+ /**
763+ * Ensures that MappedUDTCodec is able to properly parse UDTs.
764+ *
765+ * @jira_ticket JAVA-1272
766+ * @test_category object_mapper
767+ */
768+ @Test(groups = "short")
769+ public void should_parse_mapped_udt() throws Exception {
770+ MappingManager manager = new MappingManager(session());
771+ TypeCodec<Address> codec = manager.udtCodec(Address.class);
772+ Address actual = codec.parse("{street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}}");
773+ assertThat(actual).isEqualTo(new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
774+ }
775+
731776 }