Elffuss BraidHub

kikocis/java-driver public

JAVA-743: Add JSON support to QueryBuilder (#664)

This commit contains substantial contributions by Andrew Tolbert (@tolbertam).

This commit introduces 4 new features:
- Support for SELECT JSON.
- Support for INSERT JSON.
- Support for toJson() function.
- Support for fromJson() function.

It also adds tests for JAVA-743 with Jsr353JsonCodec
in module driver-extras. These tests validate json support in
QueryBuilder using Jsr353JsonCodec and
javax.json for convenience.

It also sets log4j.rootLogger to INFO in driver-extras test
log4j.properties to match driver-core.
Changesetbbd5e272a15716fe71adf593612a0870f0a3d1f734a5f0cc724e903e9c0559dd
AuthorAlexandre Dutra <adutra@users.noreply.github.com> · 2016-07-15 00:47 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-14 15:47 -07:00
Parents56dd40c2701d

Browse the files at this changeset

7 files changed

modified changelog/README.md +1 −0
@@ -3,6 +3,7 @@
33 ### 3.1.0 (in progress)
44
55 - [new feature] JAVA-1153: Add PER PARTITION LIMIT to Select QueryBuilder.
6+- [improvement] JAVA-743: Add JSON support to QueryBuilder.
67
78
89 Merged from 3.0.x branch:
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +78 −5
@@ -23,6 +23,8 @@
2323 import java.util.Arrays;
2424 import java.util.List;
2525
26+import static com.google.common.base.Preconditions.checkState;
27+
2628 /**
2729 * A built INSERT statement.
2830 */
@@ -33,6 +35,7 @@
3335 private final List<Object> values = new ArrayList<Object>();
3436 private final Options usings;
3537 private boolean ifNotExists;
38+ private String json;
3639
3740 Insert(String keyspace, String table) {
3841 this(keyspace, table, null, null);
@@ -62,11 +65,19 @@
6265 if (keyspace != null)
6366 Utils.appendName(keyspace, builder).append('.');
6467 Utils.appendName(table, builder);
65- builder.append(" (");
66- Utils.joinAndAppendNames(builder, codecRegistry, ",", names);
67- builder.append(") VALUES (");
68- Utils.joinAndAppendValues(builder, codecRegistry, ",", values, variables);
69- builder.append(')');
68+
69+ builder.append(" ");
70+ if (json != null) {
71+ builder.append("JSON '");
72+ builder.append(json);
73+ builder.append("'");
74+ } else {
75+ builder.append("(");
76+ Utils.joinAndAppendNames(builder, codecRegistry, ",", names);
77+ builder.append(") VALUES (");
78+ Utils.joinAndAppendValues(builder, codecRegistry, ",", values, variables);
79+ builder.append(')');
80+ }
7081
7182 if (ifNotExists)
7283 builder.append(" IF NOT EXISTS");
@@ -84,8 +95,12 @@
8495 * @param name the name of the column to insert/update.
8596 * @param value the value to insert/update for {@code name}.
8697 * @return this INSERT statement.
98+ * @throws IllegalStateException if this method is called and the {@link #json(String)}
99+ * method has been called before, because it's not possible
100+ * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
87101 */
88102 public Insert value(String name, Object value) {
103+ checkState(json == null, "Cannot mix INSERT JSON syntax with regular INSERT syntax");
89104 names.add(name);
90105 values.add(value);
91106 checkForBindMarkers(value);
@@ -104,6 +119,9 @@
104119 * in {@code names}.
105120 * @return this INSERT statement.
106121 * @throws IllegalArgumentException if {@code names.length != values.length}.
122+ * @throws IllegalStateException if this method is called and the {@link #json(String)}
123+ * method has been called before, because it's not possible
124+ * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
107125 */
108126 public Insert values(String[] names, Object[] values) {
109127 return values(Arrays.asList(names), Arrays.asList(values));
@@ -118,10 +136,14 @@
118136 * in {@code names}.
119137 * @return this INSERT statement.
120138 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
139+ * @throws IllegalStateException if this method is called and the {@link #json(String)}
140+ * method has been called before, because it's not possible
141+ * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
121142 */
122143 public Insert values(List<String> names, List<Object> values) {
123144 if (names.size() != values.size())
124145 throw new IllegalArgumentException(String.format("Got %d names but %d values", names.size(), values.size()));
146+ checkState(json == null, "Cannot mix INSERT JSON syntax with regular INSERT syntax");
125147 this.names.addAll(names);
126148 this.values.addAll(values);
127149 for (int i = 0; i < names.size(); i++) {
@@ -134,6 +156,57 @@
134156 return this;
135157 }
136158
159+ /**
160+ * Inserts the provided JSON string, using the {@code INSERT INTO ... JSON} syntax introduced
161+ * in Cassandra 2.2.
162+ * <p>
163+ * With INSERT statements, the new {@code JSON} keyword can be used to enable inserting a
164+ * JSON encoded map as a single row.
165+ * <p>
166+ * <strong>The provided JSON string will be appended to the query string as is.
167+ * It should NOT be surrounded by single quotes.</strong>
168+ * Its format should generally match that returned by a
169+ * {@code SELECT JSON} statement on the same table.
170+ * <p>
171+ * Note that it is not possible to insert function calls nor bind markers in the JSON string.
172+ * <h3>Case-sensitive column names</h3>
173+ * Users are required to handle case-sensitive column names
174+ * by surrounding them with double quotes.
175+ * <p>
176+ * For example, to insert into a table with two columns named “myKey” and “value”,
177+ * you would do the following:
178+ * <pre>
179+ * insertInto("mytable").json("{\"\\\"myKey\\\"\": 0, \"value\": 0}");
180+ * </pre>
181+ * This will produce the following CQL:
182+ * <pre>
183+ * INSERT INTO mytable JSON '{"\"myKey\"": 0, "value": 0}';
184+ * </pre>
185+ * <h3>Escaping quotes in column values</h3>
186+ * Double quotes should be escaped with a backslash, but single quotes should be escaped in
187+ * the CQL manner, i.e. by another single quote. For example, the column value
188+ * {@code foo"'bar} should be inserted in the JSON string
189+ * as {@code "foo\"''bar"}.
190+ * <p>
191+ * <h3>Null values and tombstones</h3>
192+ * Any columns which are omitted from the JSON string will be defaulted to a {@code NULL} value
193+ * (which will result in a tombstone being created).
194+ *
195+ * @param json the JSON string.
196+ * @return this INSERT statement.
197+ * @throws IllegalStateException if this method is called and any of the {@code value} or {@code values}
198+ * methods have been called before, because it's not possible
199+ * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
200+ * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
201+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
202+ * @see <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_using/useInsertJSON.html">Inserting JSON data</a>
203+ */
204+ public Insert json(String json) {
205+ checkState(values.isEmpty() && names.isEmpty(), "Cannot mix INSERT JSON syntax with regular INSERT syntax");
206+ this.json = json;
207+ return this;
208+ }
209+
137210 /**
138211 * Adds a new options for this INSERT statement.
139212 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +32 −0
@@ -1050,4 +1050,36 @@
10501050 public static Object column(String name) {
10511051 return new Utils.CName(name);
10521052 }
1053+
1054+ /**
1055+ * Creates a {@code fromJson()} function call.
1056+ * <p>
1057+ * Support for JSON functions has been added in Cassandra 2.2.
1058+ * The {@code fromJson()} function is similar to {@code INSERT JSON} statements,
1059+ * but applies to a single column value instead of the entire row, and
1060+ * converts a JSON-encoded string into the normal Cassandra column value.
1061+ * <p>
1062+ * It may be used in {@code INSERT} and {@code UPDATE} statements,
1063+ * but NOT in the selection clause of a {@code SELECT} statement.
1064+ * <p>
1065+ * <strong>The provided JSON string will be appended to the query string as is.
1066+ * It should NOT be surrounded by single quotes.</strong>
1067+ * <p>
1068+ * String values should be enclosed in double quotes.
1069+ * Double quotes appearing inside strings should be escaped with a backslash,
1070+ * but single quotes should be escaped in
1071+ * the CQL manner, i.e. by another single quote. For example, the column value
1072+ * {@code foo"'bar} should be inserted in the JSON string
1073+ * as {@code "foo\"''bar"}.
1074+ * <p>
1075+ * Note that it is not possible to insert function calls nor bind markers in the JSON string.
1076+ *
1077+ * @return the function call.
1078+ * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
1079+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
1080+ */
1081+ public static Object fromJson(String json) {
1082+ return fcall("fromJson", raw("'" + json + "'"));
1083+ }
1084+
10531085 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +78 −8
@@ -34,6 +34,7 @@
3434
3535 private final String table;
3636 private final boolean isDistinct;
37+ private final boolean isJson;
3738 private final List<Object> columnNames;
3839 private final Where where;
3940 private List<Ordering> orderings;
@@ -41,17 +42,18 @@
4142 private Object perPartitionLimit;
4243 private boolean allowFiltering;
4344
44- Select(String keyspace, String table, List<Object> columnNames, boolean isDistinct) {
45- this(keyspace, table, null, null, columnNames, isDistinct);
45+ Select(String keyspace, String table, List<Object> columnNames, boolean isDistinct, boolean isJson) {
46+ this(keyspace, table, null, null, columnNames, isDistinct, isJson);
4647 }
4748
48- Select(TableMetadata table, List<Object> columnNames, boolean isDistinct) {
49+ Select(TableMetadata table, List<Object> columnNames, boolean isDistinct, boolean isJson) {
4950 this(escapeId(table.getKeyspace().getName()),
5051 escapeId(table.getName()),
5152 Arrays.asList(new Object[table.getPartitionKey().size()]),
5253 table.getPartitionKey(),
5354 columnNames,
54- isDistinct);
55+ isDistinct,
56+ isJson);
5557 }
5658
5759 Select(String keyspace,
@@ -59,11 +61,13 @@
5961 List<Object> routingKeyValues,
6062 List<ColumnMetadata> partitionKey,
6163 List<Object> columnNames,
62- boolean isDistinct) {
64+ boolean isDistinct,
65+ boolean isJson) {
6366 super(keyspace, partitionKey, routingKeyValues);
6467 this.table = table;
65- this.isDistinct = isDistinct;
6668 this.columnNames = columnNames;
69+ this.isDistinct = isDistinct;
70+ this.isJson = isJson;
6771 this.where = new Where(this);
6872 }
6973
@@ -72,8 +76,13 @@
7276 StringBuilder builder = new StringBuilder();
7377
7478 builder.append("SELECT ");
79+
80+ if (isJson)
81+ builder.append("JSON ");
82+
7583 if (isDistinct)
7684 builder.append("DISTINCT ");
85+
7786 if (columnNames == null) {
7887 builder.append('*');
7988 } else {
@@ -354,6 +363,7 @@
354363
355364 List<Object> columnNames;
356365 boolean isDistinct;
366+ boolean isJson;
357367
358368 Builder() {
359369 }
@@ -372,6 +382,22 @@
372382 return this;
373383 }
374384
385+ /**
386+ * Uses JSON selection.
387+ * <p>
388+ * Cassandra 2.2 introduced JSON support to SELECT statements:
389+ * the {@code JSON} keyword can be used to return each row as a single JSON encoded map.
390+ *
391+ * @return this in-build SELECT statement.
392+ * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
393+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
394+ * @see <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_using/useQueryJSON.html">Data retrieval using JSON</a>
395+ */
396+ public Builder json() {
397+ this.isJson = true;
398+ return this;
399+ }
400+
375401 /**
376402 * Adds the table to select from.
377403 *
@@ -390,7 +416,7 @@
390416 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
391417 */
392418 public Select from(String keyspace, String table) {
393- return new Select(keyspace, table, columnNames, isDistinct);
419+ return new Select(keyspace, table, columnNames, isDistinct, isJson);
394420 }
395421
396422 /**
@@ -400,7 +426,7 @@
400426 * @return a newly built SELECT statement that selects from {@code table}.
401427 */
402428 public Select from(TableMetadata table) {
403- return new Select(table, columnNames, isDistinct);
429+ return new Select(table, columnNames, isDistinct, isJson);
404430 }
405431 }
406432
@@ -420,6 +446,23 @@
420446 return this;
421447 }
422448
449+ /**
450+ * Uses JSON selection.
451+ * <p>
452+ * Cassandra 2.2 introduced JSON support to SELECT statements:
453+ * the {@code JSON} keyword can be used to return each row as a single JSON encoded map.
454+ *
455+ * @return this in-build SELECT statement.
456+ * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
457+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
458+ * @see <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_using/useQueryJSON.html">Data retrieval using JSON</a>
459+ */
460+ @Override
461+ public Selection json() {
462+ this.isJson = true;
463+ return this;
464+ }
465+
423466 /**
424467 * Selects all columns (i.e. "SELECT * ...")
425468 *
@@ -508,6 +551,27 @@
508551 // so we add this dummy implementation to make Clirr happy.
509552 throw new UnsupportedOperationException("Not implemented. This should only happen if you've written your own implementation of Selection");
510553 }
554+
555+ /**
556+ * Creates a {@code toJson()} function call.
557+ * This is a shortcut for {@code fcall("toJson", QueryBuilder.column(name))}.
558+ * <p>
559+ * Support for JSON functions has been added in Cassandra 2.2.
560+ * The {@code toJson()} function is similar to {@code SELECT JSON} statements,
561+ * but applies to a single column value instead of the entire row,
562+ * and produces a JSON-encoded string representing the normal Cassandra column value.
563+ * <p>
564+ * It may only be used in the selection clause of a {@code SELECT} statement.
565+ *
566+ * @return the function call.
567+ * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
568+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
569+ */
570+ public SelectionOrAlias toJson(String name) {
571+ // This method should be abstract like others here. But adding an abstract method is not binary-compatible,
572+ // so we add this dummy implementation to make Clirr happy.
573+ throw new UnsupportedOperationException("Not implemented. This should only happen if you've written your own implementation of Selection");
574+ }
511575 }
512576
513577 /**
@@ -591,6 +655,7 @@
591655 return queueName(new Utils.FCall(name, parameters));
592656 }
593657
658+ @Override
594659 public SelectionOrAlias cast(Object column, DataType targetType) {
595660 return queueName(new Utils.Cast(column, targetType));
596661 }
@@ -600,6 +665,11 @@
600665 return queueName(QueryBuilder.raw(rawString));
601666 }
602667
668+ @Override
669+ public SelectionOrAlias toJson(String name) {
670+ return queueName(new Utils.FCall("toJson", new Utils.CName(name)));
671+ }
672+
603673 @Override
604674 public Select from(String keyspace, String table) {
605675 if (previousSelection != null)
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +47 −2
@@ -20,7 +20,6 @@
2020 import com.datastax.driver.core.exceptions.InvalidQueryException;
2121 import com.datastax.driver.core.exceptions.InvalidTypeException;
2222 import com.datastax.driver.core.utils.Bytes;
23-import com.datastax.driver.core.utils.CassandraVersion;
2423 import com.google.common.collect.ImmutableList;
2524 import com.google.common.collect.ImmutableMap;
2625 import com.google.common.collect.Lists;
@@ -826,7 +825,6 @@
826825 }
827826
828827 @Test(groups = "unit")
829- @CassandraVersion(major = 2.1, minor = 3)
830828 public void should_handle_nested_collections() {
831829 String query;
832830 Statement statement;
@@ -1045,4 +1043,51 @@
10451043 assertThat(e).hasMessage("A PER PARTITION LIMIT value has already been provided");
10461044 }
10471045 }
1046+ @Test(groups = "unit")
1047+ public void should_handle_select_json() throws Exception {
1048+ assertThat(
1049+ select().json().from("users").toString())
1050+ .isEqualTo("SELECT JSON * FROM users;");
1051+ assertThat(
1052+ select("id", "age").json().from("users").toString())
1053+ .isEqualTo("SELECT JSON id,age FROM users;");
1054+ assertThat(
1055+ select().json().column("id").writeTime("age").ttl("state").as("ttl").from("users").toString())
1056+ .isEqualTo("SELECT JSON id,writetime(age),ttl(state) AS ttl FROM users;");
1057+ assertThat(
1058+ select().distinct().json().column("id").from("users").toString())
1059+ .isEqualTo("SELECT JSON DISTINCT id FROM users;"); // note that the correct syntax is JSON DISTINCT
1060+ }
1061+
1062+ @Test(groups = "unit")
1063+ public void should_handle_insert_json() throws Exception {
1064+ assertThat(
1065+ insertInto("example").json("{\"id\": 0, \"tupleval\": [1, \"abc\"], \"numbers\": [1, 2, 3], \"letters\": [\"a\", \"b\", \"c\"]}").toString())
1066+ .isEqualTo("INSERT INTO example JSON '{\"id\": 0, \"tupleval\": [1, \"abc\"], \"numbers\": [1, 2, 3], \"letters\": [\"a\", \"b\", \"c\"]}';");
1067+ assertThat(
1068+ insertInto("users").json("{\"id\": \"user123\", \"\\\"Age\\\"\": 42, \"\\\"State\\\"\": \"TX\"}").toString())
1069+ .isEqualTo("INSERT INTO users JSON '{\"id\": \"user123\", \"\\\"Age\\\"\": 42, \"\\\"State\\\"\": \"TX\"}';");
1070+ }
1071+
1072+ @Test(groups = "unit")
1073+ public void should_handle_to_json() throws Exception {
1074+ assertThat(
1075+ select().toJson("id").as("id").toJson("age").as("age").from("users").toString())
1076+ .isEqualTo("SELECT toJson(id) AS id,toJson(age) AS age FROM users;");
1077+ assertThat(
1078+ select().distinct().toJson("id").as("id").from("users").toString())
1079+ .isEqualTo("SELECT DISTINCT toJson(id) AS id FROM users;");
1080+ }
1081+
1082+ @Test(groups = "unit")
1083+ public void should_handle_from_json() throws Exception {
1084+ assertThat(
1085+ update("users").with(set("age", fromJson("42"))).where(eq("id", fromJson("\"user123\""))).toString())
1086+ .isEqualTo("UPDATE users SET age=fromJson('42') WHERE id=fromJson('\"user123\"');");
1087+ assertThat(
1088+ insertInto("users").value("id", fromJson("\"user123\"")).value("age", fromJson("42")).toString())
1089+ .isEqualTo("INSERT INTO users (id,age) VALUES (fromJson('\"user123\"'),fromJson('42'));");
1090+ }
1091+
1092+
10481093 }
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +132 −5
@@ -17,6 +17,7 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.querybuilder.BuiltStatement;
20+import com.datastax.driver.core.querybuilder.QueryBuilder;
2021 import com.datastax.driver.core.utils.CassandraVersion;
2122 import org.testng.annotations.DataProvider;
2223 import org.testng.annotations.Test;
@@ -27,6 +28,7 @@
2728
2829 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2930 import static org.assertj.core.api.Assertions.assertThat;
31+import static org.assertj.core.api.Assertions.fail;
3032
3133 public class Jsr353JsonCodecTest extends CCMTestsSupport {
3234
@@ -43,11 +45,26 @@
4345
4446 private static final String notAJsonString = "this text is not json";
4547
48+ private static final String TABLE1 = "test1";
49+ private static final String TABLE2 = "test2";
50+
4651 @Override
4752 public void onTestContextInitialized() {
4853 execute(
49- "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
54+ "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))",
55+ String.format("CREATE TABLE %s (k text, \"miXeD\" text, i int, f float, PRIMARY KEY (k, \"miXeD\"))", TABLE1),
56+ insertInto(TABLE1).value("k", "key0").value(quote("miXeD"), "a").value("i", 1).value("f", 1.1).toString(),
57+ insertInto(TABLE1).value("k", "key0").value(quote("miXeD"), "b").value("i", 2).value("f", 2.5).toString(),
58+ insertInto(TABLE1).value("k", "key0").value(quote("miXeD"), "c").value("i", 3).value("f", 3.7).toString(),
59+ insertInto(TABLE1).value("k", "key0").value(quote("miXeD"), "d").value("i", 4).value("f", 5.0).toString()
5060 );
61+
62+ if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V3) >= 0) {
63+ execute(
64+ "CREATE TYPE address (street text, zipcode int, phones list<text>)",
65+ String.format("CREATE TABLE %s (k text PRIMARY KEY, v frozen<address>)", TABLE2)
66+ );
67+ }
5168 }
5269
5370 @Override
@@ -133,13 +150,13 @@
133150 @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
134151 public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException {
135152 session().execute(session().prepare(insertQuery).bind()
136- .setString(0, notAJsonString)
137- .set(1, object, JsonStructure.class)
153+ .setString(0, notAJsonString)
154+ .set(1, object, JsonStructure.class)
138155 );
139156 PreparedStatement ps = session().prepare(selectQuery);
140157 ResultSet rows = session().execute(ps.bind()
141- .setString(0, notAJsonString)
142- .set(1, object, JsonStructure.class)
158+ .setString(0, notAJsonString)
159+ .set(1, object, JsonStructure.class)
143160 );
144161 Row row = rows.one();
145162 assertRow(row, object);
@@ -158,4 +175,114 @@
158175 assertThat(row.get(1, JsonStructure.class)).isEqualTo(object);
159176 }
160177
178+ /**
179+ * Validates that the {@code select().json()} capability in {@link QueryBuilder} appropriately generates a
180+ * 'SELECT JSON' query and that the returned {@link ResultSet} has rows with a column that is parsable using
181+ * {@link Jsr353JsonCodec}.
182+ *
183+ * @jira_ticket JAVA-743
184+ * @since 3.1.0
185+ */
186+ @Test(groups = "short")
187+ @CassandraVersion(major = 2.2)
188+ public void should_support_select_json_output() throws Exception {
189+ // when
190+ ResultSet r = session().execute(select().json().from(TABLE1).where(eq("k", "key0")));
191+ // then
192+ assertThat(r.getAvailableWithoutFetching()).isEqualTo(4);
193+ for (Row row : r) {
194+ JsonStructure json = row.get(0, jsonCodec);
195+ assertThat(json).isInstanceOf(JsonObject.class);
196+ JsonObject obj = (JsonObject) json;
197+ assertThat(obj.containsKey("k")).isTrue();
198+ assertThat(obj.containsKey(quote("miXeD"))).isTrue();
199+ assertThat(obj.containsKey("i")).isTrue();
200+ assertThat(obj.containsKey("f")).isTrue();
201+
202+ assertThat(obj.getString("k")).isEqualTo("key0");
203+
204+ int i = obj.getInt("i");
205+ switch (i) {
206+ case 1:
207+ assertThat(obj.getString(quote("miXeD"))).isEqualTo("a");
208+ assertThat(obj.getJsonNumber("f").doubleValue()).isEqualTo(1.1);
209+ break;
210+ case 2:
211+ assertThat(obj.getString(quote("miXeD"))).isEqualTo("b");
212+ assertThat(obj.getJsonNumber("f").doubleValue()).isEqualTo(2.5);
213+ break;
214+ case 3:
215+ assertThat(obj.getString(quote("miXeD"))).isEqualTo("c");
216+ assertThat(obj.getJsonNumber("f").doubleValue()).isEqualTo(3.7);
217+ break;
218+ case 4:
219+ assertThat(obj.getString(quote("miXeD"))).isEqualTo("d");
220+ assertThat(obj.getJsonNumber("f").doubleValue()).isEqualTo(5.0);
221+ break;
222+ default:
223+ fail("Unexpected value for i = " + i);
224+ }
225+ }
226+ }
227+
228+ /**
229+ * Validates that the {@code insertInto().json()} capability in {@link QueryBuilder} creates a query that interprets
230+ * the input as a json document and that fetching that data back as json returns a row with a column that matches
231+ * the contents of the input json document when retrieved using get with {@link JsonStructure}.
232+ *
233+ * @jira_ticket JAVA-743
234+ * @since 3.1.0
235+ */
236+ @Test(groups = "short")
237+ @CassandraVersion(major = 2.2)
238+ public void should_support_insert_json() throws Exception {
239+ // when
240+ String key = "should_support_insert_json_with_codec_format";
241+ JsonObject input = Json.createObjectBuilder().add("k", key)
242+ .add(quote("miXeD"), "miXeDValue")
243+ .add("f", 8.6)
244+ .add("i", 4)
245+ .build();
246+ session().execute(insertInto(TABLE1).json(input.toString()));
247+ // then
248+ ResultSet r = session().execute(select().json().from(TABLE1).where(eq("k", key)));
249+ assertThat(r.getAvailableWithoutFetching()).isEqualTo(1);
250+
251+ JsonStructure output = r.one().get(0, JsonStructure.class);
252+ assertThat(output).isEqualTo(input);
253+ }
254+
255+ /**
256+ * Validates that the {@code fromJson()} and {@code toJson} capability in {@link QueryBuilder} allows specifying
257+ * json input ({@code fromJson}) and retrieval of json column output ({@code toJson}). This test inserts a row
258+ * with a UDT providing the UDT column value as json using {@code toJson} and then retrieves that column value
259+ * using {@code fromJson} and ensures the output matches the input {@link JsonStructure} for the UDT.
260+ *
261+ * @jira_ticket JAVA-743
262+ * @since 3.1.0
263+ */
264+ @Test(groups = "short")
265+ @CassandraVersion(major = 2.2)
266+ public void should_support_fromJson_and_toJson() throws Exception {
267+ String key = "should_support_fromJson_and_toJson";
268+ JsonObject inputAddr = Json.createObjectBuilder()
269+ .add("street", "1234 Ln.")
270+ .add("zipcode", 86753)
271+ .add("phones", Json.createArrayBuilder().add("555-5555").add("867-5309").build())
272+ .build();
273+
274+ // insert using fromJson on address column, which is a UDT.
275+ session().execute(insertInto(TABLE2).value("k", key).value("v", fromJson(inputAddr.toString())));
276+
277+ // retrieve using toJson on address column.
278+ ResultSet r = session().execute(select().toJson("v").as("v").column("k").from(TABLE2).where(eq("k", key)));
279+
280+ assertThat(r.getAvailableWithoutFetching()).isEqualTo(1);
281+
282+ Row row = r.one();
283+
284+ assertThat(row.getString("k")).isEqualTo(key);
285+ assertThat(row.get("v", JsonStructure.class)).isEqualTo(inputAddr);
286+ }
287+
161288 }
modified driver-extras/src/test/resources/log4j.properties +1 −1
@@ -15,7 +15,7 @@
1515 #
1616
1717 # Set root logger level to OFF and its only appender to A1.
18-log4j.rootLogger=OFF, A1
18+log4j.rootLogger=INFO, A1
1919
2020 # Adjust Scassandra's log level
2121 # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)