kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | bbd5e272a15716fe71adf593612a0870f0a3d1f734a5f0cc724e903e9c0559dd |
|---|---|
| Author | Alexandre Dutra <adutra@users.noreply.github.com> · 2016-07-15 00:47 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-07-14 15:47 -07:00 |
| Parents | 56dd40c2701d |
7 files changed
modified changelog/README.md +1 −0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ### 3.1.0 (in progress) |
| 4 | 4 | |
| 5 | 5 | - [new feature] JAVA-1153: Add PER PARTITION LIMIT to Select QueryBuilder. |
| 6 | +- [improvement] JAVA-743: Add JSON support to QueryBuilder. | |
| 6 | 7 | |
| 7 | 8 | |
| 8 | 9 | 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 @@ | ||
| 23 | 23 | import java.util.Arrays; |
| 24 | 24 | import java.util.List; |
| 25 | 25 | |
| 26 | +import static com.google.common.base.Preconditions.checkState; | |
| 27 | + | |
| 26 | 28 | /** |
| 27 | 29 | * A built INSERT statement. |
| 28 | 30 | */ |
| @@ -33,6 +35,7 @@ | ||
| 33 | 35 | private final List<Object> values = new ArrayList<Object>(); |
| 34 | 36 | private final Options usings; |
| 35 | 37 | private boolean ifNotExists; |
| 38 | + private String json; | |
| 36 | 39 | |
| 37 | 40 | Insert(String keyspace, String table) { |
| 38 | 41 | this(keyspace, table, null, null); |
| @@ -62,11 +65,19 @@ | ||
| 62 | 65 | if (keyspace != null) |
| 63 | 66 | Utils.appendName(keyspace, builder).append('.'); |
| 64 | 67 | 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 | + } | |
| 70 | 81 | |
| 71 | 82 | if (ifNotExists) |
| 72 | 83 | builder.append(" IF NOT EXISTS"); |
| @@ -84,8 +95,12 @@ | ||
| 84 | 95 | * @param name the name of the column to insert/update. |
| 85 | 96 | * @param value the value to insert/update for {@code name}. |
| 86 | 97 | * @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. | |
| 87 | 101 | */ |
| 88 | 102 | public Insert value(String name, Object value) { |
| 103 | + checkState(json == null, "Cannot mix INSERT JSON syntax with regular INSERT syntax"); | |
| 89 | 104 | names.add(name); |
| 90 | 105 | values.add(value); |
| 91 | 106 | checkForBindMarkers(value); |
| @@ -104,6 +119,9 @@ | ||
| 104 | 119 | * in {@code names}. |
| 105 | 120 | * @return this INSERT statement. |
| 106 | 121 | * @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. | |
| 107 | 125 | */ |
| 108 | 126 | public Insert values(String[] names, Object[] values) { |
| 109 | 127 | return values(Arrays.asList(names), Arrays.asList(values)); |
| @@ -118,10 +136,14 @@ | ||
| 118 | 136 | * in {@code names}. |
| 119 | 137 | * @return this INSERT statement. |
| 120 | 138 | * @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. | |
| 121 | 142 | */ |
| 122 | 143 | public Insert values(List<String> names, List<Object> values) { |
| 123 | 144 | if (names.size() != values.size()) |
| 124 | 145 | 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"); | |
| 125 | 147 | this.names.addAll(names); |
| 126 | 148 | this.values.addAll(values); |
| 127 | 149 | for (int i = 0; i < names.size(); i++) { |
| @@ -134,6 +156,57 @@ | ||
| 134 | 156 | return this; |
| 135 | 157 | } |
| 136 | 158 | |
| 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 | + | |
| 137 | 210 | /** |
| 138 | 211 | * Adds a new options for this INSERT statement. |
| 139 | 212 | * |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +32 −0
| @@ -1050,4 +1050,36 @@ | ||
| 1050 | 1050 | public static Object column(String name) { |
| 1051 | 1051 | return new Utils.CName(name); |
| 1052 | 1052 | } |
| 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 | + | |
| 1053 | 1085 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +78 −8
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | |
| 35 | 35 | private final String table; |
| 36 | 36 | private final boolean isDistinct; |
| 37 | + private final boolean isJson; | |
| 37 | 38 | private final List<Object> columnNames; |
| 38 | 39 | private final Where where; |
| 39 | 40 | private List<Ordering> orderings; |
| @@ -41,17 +42,18 @@ | ||
| 41 | 42 | private Object perPartitionLimit; |
| 42 | 43 | private boolean allowFiltering; |
| 43 | 44 | |
| 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); | |
| 46 | 47 | } |
| 47 | 48 | |
| 48 | - Select(TableMetadata table, List<Object> columnNames, boolean isDistinct) { | |
| 49 | + Select(TableMetadata table, List<Object> columnNames, boolean isDistinct, boolean isJson) { | |
| 49 | 50 | this(escapeId(table.getKeyspace().getName()), |
| 50 | 51 | escapeId(table.getName()), |
| 51 | 52 | Arrays.asList(new Object[table.getPartitionKey().size()]), |
| 52 | 53 | table.getPartitionKey(), |
| 53 | 54 | columnNames, |
| 54 | - isDistinct); | |
| 55 | + isDistinct, | |
| 56 | + isJson); | |
| 55 | 57 | } |
| 56 | 58 | |
| 57 | 59 | Select(String keyspace, |
| @@ -59,11 +61,13 @@ | ||
| 59 | 61 | List<Object> routingKeyValues, |
| 60 | 62 | List<ColumnMetadata> partitionKey, |
| 61 | 63 | List<Object> columnNames, |
| 62 | - boolean isDistinct) { | |
| 64 | + boolean isDistinct, | |
| 65 | + boolean isJson) { | |
| 63 | 66 | super(keyspace, partitionKey, routingKeyValues); |
| 64 | 67 | this.table = table; |
| 65 | - this.isDistinct = isDistinct; | |
| 66 | 68 | this.columnNames = columnNames; |
| 69 | + this.isDistinct = isDistinct; | |
| 70 | + this.isJson = isJson; | |
| 67 | 71 | this.where = new Where(this); |
| 68 | 72 | } |
| 69 | 73 | |
| @@ -72,8 +76,13 @@ | ||
| 72 | 76 | StringBuilder builder = new StringBuilder(); |
| 73 | 77 | |
| 74 | 78 | builder.append("SELECT "); |
| 79 | + | |
| 80 | + if (isJson) | |
| 81 | + builder.append("JSON "); | |
| 82 | + | |
| 75 | 83 | if (isDistinct) |
| 76 | 84 | builder.append("DISTINCT "); |
| 85 | + | |
| 77 | 86 | if (columnNames == null) { |
| 78 | 87 | builder.append('*'); |
| 79 | 88 | } else { |
| @@ -354,6 +363,7 @@ | ||
| 354 | 363 | |
| 355 | 364 | List<Object> columnNames; |
| 356 | 365 | boolean isDistinct; |
| 366 | + boolean isJson; | |
| 357 | 367 | |
| 358 | 368 | Builder() { |
| 359 | 369 | } |
| @@ -372,6 +382,22 @@ | ||
| 372 | 382 | return this; |
| 373 | 383 | } |
| 374 | 384 | |
| 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 | + | |
| 375 | 401 | /** |
| 376 | 402 | * Adds the table to select from. |
| 377 | 403 | * |
| @@ -390,7 +416,7 @@ | ||
| 390 | 416 | * @return a newly built SELECT statement that selects from {@code keyspace.table}. |
| 391 | 417 | */ |
| 392 | 418 | public Select from(String keyspace, String table) { |
| 393 | - return new Select(keyspace, table, columnNames, isDistinct); | |
| 419 | + return new Select(keyspace, table, columnNames, isDistinct, isJson); | |
| 394 | 420 | } |
| 395 | 421 | |
| 396 | 422 | /** |
| @@ -400,7 +426,7 @@ | ||
| 400 | 426 | * @return a newly built SELECT statement that selects from {@code table}. |
| 401 | 427 | */ |
| 402 | 428 | public Select from(TableMetadata table) { |
| 403 | - return new Select(table, columnNames, isDistinct); | |
| 429 | + return new Select(table, columnNames, isDistinct, isJson); | |
| 404 | 430 | } |
| 405 | 431 | } |
| 406 | 432 | |
| @@ -420,6 +446,23 @@ | ||
| 420 | 446 | return this; |
| 421 | 447 | } |
| 422 | 448 | |
| 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 | + | |
| 423 | 466 | /** |
| 424 | 467 | * Selects all columns (i.e. "SELECT * ...") |
| 425 | 468 | * |
| @@ -508,6 +551,27 @@ | ||
| 508 | 551 | // so we add this dummy implementation to make Clirr happy. |
| 509 | 552 | throw new UnsupportedOperationException("Not implemented. This should only happen if you've written your own implementation of Selection"); |
| 510 | 553 | } |
| 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 | + } | |
| 511 | 575 | } |
| 512 | 576 | |
| 513 | 577 | /** |
| @@ -591,6 +655,7 @@ | ||
| 591 | 655 | return queueName(new Utils.FCall(name, parameters)); |
| 592 | 656 | } |
| 593 | 657 | |
| 658 | + @Override | |
| 594 | 659 | public SelectionOrAlias cast(Object column, DataType targetType) { |
| 595 | 660 | return queueName(new Utils.Cast(column, targetType)); |
| 596 | 661 | } |
| @@ -600,6 +665,11 @@ | ||
| 600 | 665 | return queueName(QueryBuilder.raw(rawString)); |
| 601 | 666 | } |
| 602 | 667 | |
| 668 | + @Override | |
| 669 | + public SelectionOrAlias toJson(String name) { | |
| 670 | + return queueName(new Utils.FCall("toJson", new Utils.CName(name))); | |
| 671 | + } | |
| 672 | + | |
| 603 | 673 | @Override |
| 604 | 674 | public Select from(String keyspace, String table) { |
| 605 | 675 | if (previousSelection != null) |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +47 −2
| @@ -20,7 +20,6 @@ | ||
| 20 | 20 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 21 | 21 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 22 | 22 | import com.datastax.driver.core.utils.Bytes; |
| 23 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 24 | 23 | import com.google.common.collect.ImmutableList; |
| 25 | 24 | import com.google.common.collect.ImmutableMap; |
| 26 | 25 | import com.google.common.collect.Lists; |
| @@ -826,7 +825,6 @@ | ||
| 826 | 825 | } |
| 827 | 826 | |
| 828 | 827 | @Test(groups = "unit") |
| 829 | - @CassandraVersion(major = 2.1, minor = 3) | |
| 830 | 828 | public void should_handle_nested_collections() { |
| 831 | 829 | String query; |
| 832 | 830 | Statement statement; |
| @@ -1045,4 +1043,51 @@ | ||
| 1045 | 1043 | assertThat(e).hasMessage("A PER PARTITION LIMIT value has already been provided"); |
| 1046 | 1044 | } |
| 1047 | 1045 | } |
| 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 | + | |
| 1048 | 1093 | } |
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +132 −5
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.querybuilder.BuiltStatement; |
| 20 | +import com.datastax.driver.core.querybuilder.QueryBuilder; | |
| 20 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | 22 | import org.testng.annotations.DataProvider; |
| 22 | 23 | import org.testng.annotations.Test; |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | |
| 28 | 29 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 29 | 30 | import static org.assertj.core.api.Assertions.assertThat; |
| 31 | +import static org.assertj.core.api.Assertions.fail; | |
| 30 | 32 | |
| 31 | 33 | public class Jsr353JsonCodecTest extends CCMTestsSupport { |
| 32 | 34 | |
| @@ -43,11 +45,26 @@ | ||
| 43 | 45 | |
| 44 | 46 | private static final String notAJsonString = "this text is not json"; |
| 45 | 47 | |
| 48 | + private static final String TABLE1 = "test1"; | |
| 49 | + private static final String TABLE2 = "test2"; | |
| 50 | + | |
| 46 | 51 | @Override |
| 47 | 52 | public void onTestContextInitialized() { |
| 48 | 53 | 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() | |
| 50 | 60 | ); |
| 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 | + } | |
| 51 | 68 | } |
| 52 | 69 | |
| 53 | 70 | @Override |
| @@ -133,13 +150,13 @@ | ||
| 133 | 150 | @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest") |
| 134 | 151 | public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException { |
| 135 | 152 | 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) | |
| 138 | 155 | ); |
| 139 | 156 | PreparedStatement ps = session().prepare(selectQuery); |
| 140 | 157 | 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) | |
| 143 | 160 | ); |
| 144 | 161 | Row row = rows.one(); |
| 145 | 162 | assertRow(row, object); |
| @@ -158,4 +175,114 @@ | ||
| 158 | 175 | assertThat(row.get(1, JsonStructure.class)).isEqualTo(object); |
| 159 | 176 | } |
| 160 | 177 | |
| 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 | + | |
| 161 | 288 | } |
modified driver-extras/src/test/resources/log4j.properties +1 −1
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | # |
| 16 | 16 | |
| 17 | 17 | # Set root logger level to OFF and its only appender to A1. |
| 18 | -log4j.rootLogger=OFF, A1 | |
| 18 | +log4j.rootLogger=INFO, A1 | |
| 19 | 19 | |
| 20 | 20 | # Adjust Scassandra's log level |
| 21 | 21 | # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both) |