Elffuss BraidHub

kikocis/java-driver public

Merge pull request #456 from datastax/java918

JAVA-918: Allow MV's select statements to be more complex.
Changeset7d40d0865c77d2a2eb78ae08d5030e7ca9712c6857baab337bfc4e9f1dc70f66
AuthorAleksey Yeschenko <aleksey@yeschenko.com> · 2015-09-19 16:15 +01:00
CommitterAleksey Yeschenko <aleksey@yeschenko.com> · 2015-09-19 16:15 +01:00
Parentsa18d9fe5715a, 1ad61d56b9de

Browse the files at this changeset

3 files changed

modified driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java +11 −24
@@ -18,14 +18,11 @@
1818
1919 import java.util.*;
2020
21-import com.google.common.base.Function;
22-import com.google.common.base.Joiner;
2321 import com.google.common.base.Objects;
22+
2423 import org.slf4j.Logger;
2524 import org.slf4j.LoggerFactory;
2625
27-import static com.google.common.collect.Iterables.transform;
28-
2926 /**
3027 * An immutable representation of a materialized view.
3128 * Materialized views are available starting from Cassandra 3.0.
@@ -38,6 +35,8 @@
3835
3936 private final boolean includeAllColumns;
4037
38+ private final String whereClause;
39+
4140 private MaterializedViewMetadata(
4241 KeyspaceMetadata keyspace,
4342 TableMetadata baseTable,
@@ -47,12 +46,14 @@
4746 List<ColumnMetadata> clusteringColumns,
4847 Map<String, ColumnMetadata> columns,
4948 boolean includeAllColumns,
49+ String whereClause,
5050 Options options,
5151 List<Order> clusteringOrder,
5252 VersionNumber cassandraVersion) {
5353 super(keyspace, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
5454 this.baseTable = baseTable;
5555 this.includeAllColumns = includeAllColumns;
56+ this.whereClause = whereClause;
5657 }
5758
5859 static MaterializedViewMetadata build(KeyspaceMetadata keyspace, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion) {
@@ -69,6 +70,7 @@
6970
7071 UUID id = row.getUUID("id");
7172 boolean includeAllColumns = row.getBool("include_all_columns");
73+ String whereClause = row.getString("where_clause");
7274
7375 int partitionKeySize = findCollectionSize(rawCols.values(), ColumnMetadata.Raw.Kind.PARTITION_KEY);
7476 int clusteringSize = findCollectionSize(rawCols.values(), ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN);
@@ -92,7 +94,7 @@
9294
9395 MaterializedViewMetadata view = new MaterializedViewMetadata(
9496 keyspace, baseTable, name, id, partitionKey, clusteringColumns, columns,
95- includeAllColumns, options, clusteringOrder, cassandraVersion);
97+ includeAllColumns, whereClause, options, clusteringOrder, cassandraVersion);
9698
9799 // We use this temporary set just so non PK columns are added in lexicographical order, which is the one of a
98100 // 'SELECT * FROM ...'
@@ -147,13 +149,6 @@
147149 String keyspaceName = Metadata.escapeId(keyspace.getName());
148150 String baseTableName = Metadata.escapeId(baseTable.getName());
149151 String viewName = Metadata.escapeId(name);
150- String whereClause = Joiner.on(" AND ").join(transform(getPartitionKey(), new Function<ColumnMetadata, String>() {
151- @Override
152- public String apply(ColumnMetadata input) {
153- return Metadata.escapeId(input.getName()) + " IS NOT NULL";
154- }
155- }));
156-
157152
158153 StringBuilder sb = new StringBuilder();
159154 sb.append("CREATE MATERIALIZED VIEW ")
@@ -180,21 +175,14 @@
180175 newLine(sb.append("FROM ").append(keyspaceName).append('.').append(baseTableName).append(" "), formatted);
181176
182177 // WHERE
183- newLine(sb.append("WHERE "), formatted);
184- Iterator<ColumnMetadata> it = getPrimaryKey().iterator();
185- while(it.hasNext()) {
186- ColumnMetadata column = it.next();
187- sb.append(spaces(4, formatted)).append(Metadata.escapeId(column.getName()));
188- sb.append(" IS NOT NULL");
189- if(it.hasNext()) sb.append(" AND");
190- sb.append(" ");
191- newLine(sb, formatted);
192- }
178+ // the CQL grammar allows missing WHERE clauses, although C* currently disallows it
179+ if (whereClause != null && !whereClause.isEmpty())
180+ newLine(sb.append("WHERE ").append(whereClause).append(' '), formatted);
193181
194182 // PK
195183 sb.append("PRIMARY KEY (");
196184 if (partitionKey.size() == 1) {
197- sb.append(partitionKey.get(0).getName());
185+ sb.append(Metadata.escapeId(partitionKey.get(0).getName()));
198186 } else {
199187 sb.append('(');
200188 boolean first = true;
@@ -210,7 +198,6 @@
210198 for (ColumnMetadata cm : clusteringColumns)
211199 sb.append(", ").append(Metadata.escapeId(cm.getName()));
212200 sb.append(')');
213- newLine(sb, formatted);
214201
215202 appendOptions(sb, formatted);
216203 return sb.toString();
modified driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java +24 −13
@@ -29,6 +29,12 @@
2929 @CassandraVersion(major = 3)
3030 public class MaterializedViewMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3131
32+ /**
33+ * Validates that a materialized view is properly retrieved and parsed.
34+ *
35+ * @test_category metadata,materialized_view
36+ * @jira_ticket JAVA-825
37+ */
3238 @Test(groups = "short")
3339 public void should_create_view_metadata() {
3440
@@ -75,27 +81,31 @@
7581 assertThat(mv.getColumns().get(3)).isNotNull().hasName("score").isClusteringColumn().hasClusteringOrder(DESC);
7682 assertThat(mv.getColumns().get(4)).isNotNull().hasName("user").isClusteringColumn();
7783 assertThat(mv.getColumns().get(5)).isNotNull().hasName("day").isClusteringColumn();
78-
7984 assertThat(mv.asCQLQuery(false)).contains(createMV);
80-
8185 }
8286
87+ /**
88+ * Validates that a materialized view is properly retrieved and parsed when using quoted identifiers.
89+ *
90+ * @test_category metadata,materialized_view
91+ * @jira_ticket JAVA-825
92+ */
8393 @Test(groups = "short")
84- public void should_create_view_metadata_with_case_sensitive_column_names() {
94+ public void should_create_view_metadata_with_quoted_identifiers() {
8595 // given
8696 String createTable = String.format(
8797 "CREATE TABLE %s.t1 ("
8898 + "\"theKey\" int, "
89- + "\"theClustering\" int, "
90- + "\"theValue\" int, "
91- + "PRIMARY KEY (\"theKey\", \"theClustering\"))",
99+ + "\"the;Clustering\" int, "
100+ + "\"the Value\" int, "
101+ + "PRIMARY KEY (\"theKey\", \"the;Clustering\"))",
92102 keyspace);
93103 String createMV = String.format(
94104 "CREATE MATERIALIZED VIEW %s.mv1 AS "
95- + "SELECT \"theKey\", \"theClustering\", \"theValue\" "
105+ + "SELECT \"theKey\", \"the;Clustering\", \"the Value\" "
96106 + "FROM %s.t1 "
97- + "WHERE \"theKey\" IS NOT NULL AND \"theClustering\" IS NOT NULL AND \"theValue\" IS NOT NULL "
98- + "PRIMARY KEY (\"theKey\", \"theClustering\")",
107+ + "WHERE \"theKey\" IS NOT NULL AND \"the;Clustering\" IS NOT NULL AND \"the Value\" IS NOT NULL "
108+ + "PRIMARY KEY (\"theKey\", \"the;Clustering\")",
99109 keyspace, keyspace);
100110 // when
101111 session.execute(createTable);
@@ -105,12 +115,13 @@
105115 MaterializedViewMetadata mv = cluster.getMetadata().getKeyspace(keyspace).getMaterializedView("mv1");
106116 assertThat(table).isNotNull().hasName("t1").hasMaterializedView(mv).hasNumberOfColumns(3);
107117 assertThat(table.getColumns().get(0)).isNotNull().hasName("theKey").isPartitionKey().hasType(cint());
108- assertThat(table.getColumns().get(1)).isNotNull().hasName("theClustering").isClusteringColumn().hasType(cint());
109- assertThat(table.getColumns().get(2)).isNotNull().hasName("theValue").isRegularColumn().hasType(cint());
118+ assertThat(table.getColumns().get(1)).isNotNull().hasName("the;Clustering").isClusteringColumn().hasType(cint());
119+ assertThat(table.getColumns().get(2)).isNotNull().hasName("the Value").isRegularColumn().hasType(cint());
110120 assertThat(mv).isNotNull().hasName("mv1").hasBaseTable(table).hasNumberOfColumns(3);
111121 assertThat(mv.getColumns().get(0)).isNotNull().hasName("theKey").isPartitionKey().hasType(cint());
112- assertThat(mv.getColumns().get(1)).isNotNull().hasName("theClustering").isClusteringColumn().hasType(cint());
113- assertThat(mv.getColumns().get(2)).isNotNull().hasName("theValue").isRegularColumn().hasType(cint());
122+ assertThat(mv.getColumns().get(1)).isNotNull().hasName("the;Clustering").isClusteringColumn().hasType(cint());
123+ assertThat(mv.getColumns().get(2)).isNotNull().hasName("the Value").isRegularColumn().hasType(cint());
124+ assertThat(mv.asCQLQuery(false)).contains(createMV);
114125 }
115126
116127 @Override
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +279 −0
@@ -0,0 +1,279 @@
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 java.util.Collection;
19+import java.util.Iterator;
20+
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import static com.google.common.collect.Lists.newArrayList;
25+import static org.assertj.core.api.Assertions.assertThat;
26+
27+import com.datastax.driver.core.CCMBridge;
28+import com.datastax.driver.core.utils.CassandraVersion;
29+import com.datastax.driver.mapping.annotations.Accessor;
30+import com.datastax.driver.mapping.annotations.Param;
31+import com.datastax.driver.mapping.annotations.Query;
32+import com.datastax.driver.mapping.annotations.Table;
33+
34+@CassandraVersion(major=3.0)
35+public class MapperMaterializedViewTest extends CCMBridge.PerClassSingleNodeCluster{
36+
37+ @Override
38+ protected Collection<String> getTableDefinitions() {
39+ // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views
40+ return newArrayList(
41+ "CREATE TABLE scores (user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY(user, game, year, month, day))",
42+ "CREATE MATERIALIZED VIEW alltimehigh AS\n"
43+ + " SELECT * FROM scores\n"
44+ + " WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL\n"
45+ + " PRIMARY KEY (game, score, user, year, month, day)\n"
46+ + " WITH CLUSTERING ORDER BY (score desc)",
47+ "CREATE MATERIALIZED VIEW dailyhigh AS\n"
48+ + " SELECT * FROM scores\n"
49+ + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL\n"
50+ + " PRIMARY KEY ((game, year, month, day), score, user)\n"
51+ + " WITH CLUSTERING ORDER BY (score DESC)",
52+ "CREATE MATERIALIZED VIEW monthlyhigh AS\n"
53+ + " SELECT * FROM scores\n"
54+ + " WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL\n"
55+ + " PRIMARY KEY ((game, year, month), score, user, day)\n"
56+ + " WITH CLUSTERING ORDER BY (score DESC)",
57+ "CREATE MATERIALIZED VIEW filtereduserhigh AS\n"
58+ + " SELECT * FROM scores\n"
59+ + " WHERE user in ('jbellis', 'pcmanus') AND game IS NOT NULL AND score IS NOT NULL AND year is NOT NULL AND day is not NULL and month IS NOT NULL\n"
60+ + " PRIMARY KEY (game, score, user, year, month, day)\n"
61+ + " WITH CLUSTERING ORDER BY (score DESC)",
62+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 5, 1, 4000)",
63+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 5, 3, 1750)",
64+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('yukim', 'Coup', 2015, 5, 3, 2250)",
65+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 5, 3, 500)",
66+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('iamaleksey', 'Coup', 2015, 6, 1, 2500)",
67+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('tjake', 'Coup', 2015, 6, 2, 1000)",
68+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Coup', 2015, 6, 2, 2000)",
69+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jmckenzie', 'Coup', 2015, 6, 9, 2700)",
70+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Coup', 2015, 6, 20, 3500)",
71+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Checkers', 2015, 6, 20, 1200)",
72+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('jbellis', 'Chess', 2015, 6, 21, 3500)",
73+ "INSERT INTO scores (user, game, year, month, day, score) VALUES ('pcmanus', 'Chess', 2015, 1, 25, 3200)"
74+ );
75+ }
76+
77+ private ScoreAccessor accessor;
78+
79+ @BeforeMethod(groups="short")
80+ public void setUp() {
81+ accessor = new MappingManager(session).createAccessor(ScoreAccessor.class);
82+ }
83+
84+ /**
85+ * Validates that an accessor properly maps a single entity over a result from a materialized
86+ * view.
87+ *
88+ * @test_category materialized_view,mapper
89+ */
90+ @Test(groups="short")
91+ public void should_access_single_entity() {
92+ Score score = accessor.allTimeHigh("Coup");
93+
94+ assertThat(score).isEqualTo(new Score("pcmanus", "Coup", 2015, 5, 1, 4000));
95+ }
96+
97+ /**
98+ * Validates that an accessor properly maps to a Result from a materialized
99+ * view.
100+ *
101+ * @test_category materialized_view,mapper
102+ */
103+ @Test(groups="short")
104+ public void should_access_mapped_result() {
105+ Result<Score> scores = accessor.dailyHigh("Coup", 2015, 6, 2);
106+
107+ Iterator<Score> iterator = scores.iterator();
108+ assertThat(iterator.next()).isEqualTo(new Score("pcmanus", "Coup", 2015, 6, 2, 2000));
109+ assertThat(iterator.next()).isEqualTo(new Score("tjake", "Coup", 2015, 6, 2, 1000));
110+ assertThat(scores.isExhausted());
111+ }
112+
113+ /**
114+ * Validates that an accessor properly maps to a Result from a materialized
115+ * view given a range criteria query.
116+ *
117+ * @test_category materialized_view,mapper
118+ */
119+ @Test(groups="short")
120+ public void should_access_mapped_result_range() {
121+ Result<Score> scores = accessor.monthlyHighRange("Coup", 2015, 6, 2500, 3500);
122+
123+ Iterator<Score> iterator = scores.iterator();
124+ assertThat(iterator.next()).isEqualTo(new Score("jbellis", "Coup", 2015, 6, 20, 3500));
125+ assertThat(iterator.next()).isEqualTo(new Score("jmckenzie", "Coup", 2015, 6, 9, 2700));
126+ assertThat(iterator.next()).isEqualTo(new Score("iamaleksey", "Coup", 2015, 6, 1, 2500));
127+ assertThat(scores.isExhausted());
128+ }
129+
130+ /**
131+ * Validates that an accessor properly maps to a Result from a materialized
132+ * view that is filtered on a primary key.
133+ *
134+ * @test_category materialized_view,mapper
135+ */
136+ @Test(groups="short")
137+ public void should_access_filtered_user_high() {
138+ Result<Score> scores = accessor.filteredUserHigh("Chess");
139+
140+ Iterator<Score> iterator = scores.iterator();
141+ assertThat(iterator.next()).isEqualTo(new Score("jbellis", "Chess", 2015, 6, 21, 3500));
142+ assertThat(iterator.next()).isEqualTo(new Score("pcmanus", "Chess", 2015, 1, 25, 3200));
143+ assertThat(scores.isExhausted());
144+ }
145+
146+ @Accessor
147+ public interface ScoreAccessor {
148+ @Query("select * from alltimehigh where game=:game")
149+ Score allTimeHigh(@Param("game") String game);
150+
151+ @Query("select * from monthlyhigh where game=? and year=? and month=? and score >= ? and score <= ?")
152+ Result<Score> monthlyHighRange(String game, int year, int month, int lowScore, int highScore);
153+
154+ @Query("select * from dailyhigh where game=? and year=? and month=? and day=?")
155+ Result<Score> dailyHigh(String game, int year, int month, int day);
156+
157+ @Query("select * from filtereduserhigh where game=:game")
158+ Result<Score> filteredUserHigh(String game);
159+ }
160+
161+ @Table(name="scores")
162+ public static class Score {
163+ String user;
164+
165+ String game;
166+
167+ int year;
168+
169+ int month;
170+
171+ int day;
172+
173+ int score;
174+
175+ public Score() {}
176+
177+ public Score(String user, String game, int year, int month, int day, int score) {
178+ this.user = user;
179+ this.game = game;
180+ this.year = year;
181+ this.month = month;
182+ this.day = day;
183+ this.score = score;
184+ }
185+
186+ public String getUser() {
187+ return user;
188+ }
189+
190+ public void setUser(String user) {
191+ this.user = user;
192+ }
193+
194+ public String getGame() {
195+ return game;
196+ }
197+
198+ public void setGame(String game) {
199+ this.game = game;
200+ }
201+
202+ public int getYear() {
203+ return year;
204+ }
205+
206+ public void setYear(int year) {
207+ this.year = year;
208+ }
209+
210+ public int getMonth() {
211+ return month;
212+ }
213+
214+ public void setMonth(int month) {
215+ this.month = month;
216+ }
217+
218+ public int getDay() {
219+ return day;
220+ }
221+
222+ public void setDay(int day) {
223+ this.day = day;
224+ }
225+
226+ public int getScore() {
227+ return score;
228+ }
229+
230+ public void setScore(int score) {
231+ this.score = score;
232+ }
233+
234+ @Override
235+ public String toString() {
236+ return "Score{" +
237+ "user='" + user + '\'' +
238+ ", game='" + game + '\'' +
239+ ", year=" + year +
240+ ", month=" + month +
241+ ", day=" + day +
242+ ", score=" + score +
243+ '}';
244+ }
245+
246+ @Override
247+ public boolean equals(Object o) {
248+ if (this == o)
249+ return true;
250+ if (!(o instanceof Score))
251+ return false;
252+
253+ Score score1 = (Score)o;
254+
255+ if (year != score1.year)
256+ return false;
257+ if (month != score1.month)
258+ return false;
259+ if (day != score1.day)
260+ return false;
261+ if (score != score1.score)
262+ return false;
263+ if (!user.equals(score1.user))
264+ return false;
265+ return game.equals(score1.game);
266+ }
267+
268+ @Override
269+ public int hashCode() {
270+ int result = user.hashCode();
271+ result = 31 * result + game.hashCode();
272+ result = 31 * result + year;
273+ result = 31 * result + month;
274+ result = 31 * result + day;
275+ result = 31 * result + score;
276+ return result;
277+ }
278+ }
279+}