Elffuss BraidHub

kikocis/java-driver public

Merge pull request #430 from datastax/java875

JAVA-875: Move secondary index metadata out of column definitions.
Changesetfd4220a09b4ea156892ad64848e5353f85a1c6a8b06f527743616a15082dc3a6
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-24 17:24 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-24 17:24 +02:00
Parentse039b363026c, e82ad000a95f

Browse the files at this changeset

12 files changed

modified changelog/README.md +3 −0
@@ -2,6 +2,9 @@
22
33 ### 3.0.0-alpha2 (in progress)
44
5+- [new feature] Move secondary index metadata out of column definitions
6+ (JAVA-875, JAVA-882).
7+
58 Merged from 2.2 branch:
69
710 - [bug] Propagate CodecRegistry to nested UDTs (JAVA-847)
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +32 −202
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Collections;
20-import java.util.HashMap;
21-import java.util.Iterator;
22-import java.util.Map;
18+import java.util.*;
2319 import java.util.Map.Entry;
2420
21+import com.google.common.base.Function;
22+import com.google.common.collect.ImmutableMap;
23+import com.google.common.collect.Maps;
24+
2525 /**
2626 * Describes a Column.
2727 */
@@ -35,30 +35,29 @@
3535 static final String INDEX_TYPE = "index_type";
3636 static final String INDEX_OPTIONS = "index_options";
3737 static final String INDEX_NAME = "index_name";
38- private static final String CUSTOM_INDEX_CLASS = "class_name";
3938
40- private static final String INDEX_MAP_KEYS = "index_keys";
41- private static final String INDEX_MAP_ENTRIES = "index_keys_and_values";
4239 private final TableMetadata table;
4340 private final String name;
4441 private final DataType type;
45- private final IndexMetadata index;
4642 private final boolean isStatic;
4743
48- private ColumnMetadata(TableMetadata table, String name, DataType type, boolean isStatic, Map<String, String> indexColumns) {
44+ // this is the "reverse" side of the many-to-many relationship
45+ // between columns and indexes, and is updated only after the column is created
46+ final Map<String, IndexMetadata> indexes = new LinkedHashMap<String, IndexMetadata>();
47+
48+ private ColumnMetadata(TableMetadata table, String name, DataType type, boolean isStatic) {
4949 this.table = table;
5050 this.name = name;
5151 this.type = type;
5252 this.isStatic = isStatic;
53- this.index = IndexMetadata.build(this, indexColumns);
5453 }
5554
5655 static ColumnMetadata fromRaw(TableMetadata tm, Raw raw) {
57- return new ColumnMetadata(tm, raw.name, raw.dataType, raw.kind == Raw.Kind.STATIC, raw.indexColumns);
56+ return new ColumnMetadata(tm, raw.name, raw.dataType, raw.kind == Raw.Kind.STATIC);
5857 }
5958
6059 static ColumnMetadata forAlias(TableMetadata tm, String name, DataType type) {
61- return new ColumnMetadata(tm, name, type, false, Collections.<String, String>emptyMap());
60+ return new ColumnMetadata(tm, name, type, false);
6261 }
6362
6463 /**
@@ -88,16 +87,6 @@
8887 return type;
8988 }
9089
91- /**
92- * Returns the indexing metadata on this column if the column is indexed.
93- *
94- * @return the metadata on the column index if the column is indexed,
95- * {@code null} otherwise.
96- */
97- public IndexMetadata getIndex() {
98- return index;
99- }
100-
10190 /**
10291 * Whether this column is a static column.
10392 *
@@ -108,186 +97,25 @@
10897 }
10998
11099 /**
111- * Metadata on a column index.
100+ * Returns metadata on a index on this column.
101+ *
102+ * @param name the name of the index to retrieve ({@code name} will be
103+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
104+ * see {@link Metadata#quote}).
105+ * @return the metadata for the {@code name} index if it exists, or
106+ * {@code null} otherwise.
112107 */
113- public static class IndexMetadata {
114-
115- private final ColumnMetadata column;
116- private final String name;
117- private final Map<String, String> indexOptions;
118-
119- private IndexMetadata(ColumnMetadata column, String name) {
120- this(column, name, null);
121- }
122-
123- private IndexMetadata(ColumnMetadata column, String name, Map<String, String> indexOptions) {
124- this.column = column;
125- this.name = name;
126- this.indexOptions = indexOptions;
127- }
128-
129- /**
130- * Returns the column this index metadata refers to.
131- *
132- * @return the column this index metadata refers to.
133- */
134- public ColumnMetadata getIndexedColumn() {
135- return column;
136- }
137-
138- /**
139- * Returns the index name.
140- *
141- * @return the index name.
142- */
143- public String getName() {
144- return name;
145- }
146-
147- /**
148- * Returns whether this index is a custom one.
149- * <p>
150- * If it is indeed a custom index, {@link #getIndexClassName} will
151- * return the name of the class used in Cassandra to implement that
152- * index.
153- *
154- * @return {@code true} if this metadata represents a custom index.
155- */
156- public boolean isCustomIndex() {
157- return getIndexClassName() != null;
158- }
159-
160- /**
161- * The name of the class used to implement the custom index, if it is one.
162- *
163- * @return the name of the class used Cassandra side to implement this
164- * custom index if {@code isCustomIndex() == true}, {@code null} otherwise.
165- */
166- public String getIndexClassName() {
167- return getOption(CUSTOM_INDEX_CLASS);
168- }
169-
170- /**
171- * Return whether this index is a 'KEYS' index on a map, e.g.,
172- * CREATE INDEX ON mytable (KEYS(mymap))
173- *
174- * @return {@code true} if this is a 'KEYS' index on a map.
175- */
176- public boolean isKeys() {
177- return getOption(INDEX_MAP_KEYS) != null;
178- }
179-
180- /**
181- * Return whether this index is a 'FULL' index on a frozen collection, e.g.,
182- * CREATE INDEX ON mytable (FULL(mymap))
183- *
184- * @return {@code true} if this is a 'FULL' index on a frozen collection.
185- */
186- public boolean isFull() {
187- /*
188- * This check is analogous to the Cassandra counterpart
189- * in IndexTarget#fromColumnDefinition.
190- */
191- return !isKeys()
192- && !isEntries()
193- && column.getType() instanceof DataType.CollectionType
194- && column.getType().isFrozen();
195- }
196-
197- /**
198- * Return whether this index is a 'ENTRIES' index on a map, e.g.,
199- * CREATE INDEX ON mytable (ENTRIES(mymap))
200- *
201- * @return {@code true} if this is an 'ENTRIES' index on a map.
202- */
203- public boolean isEntries() {
204- return getOption(INDEX_MAP_ENTRIES) != null;
205- }
206-
207- /**
208- * Return the value for the given option name.
209- *
210- * @param name Option name
211- * @return Option value
212- */
213- public String getOption(String name) {
214- return indexOptions != null ? indexOptions.get(name) : null;
215- }
216-
217- /**
218- * Returns a CQL query representing this index.
219- *
220- * This method returns a single 'CREATE INDEX' query corresponding to
221- * this index definition.
222- *
223- * @return the 'CREATE INDEX' query corresponding to this index.
224- */
225- public String asCQLQuery() {
226- TableMetadata table = column.getTable();
227- String ksName = Metadata.escapeId(table.getKeyspace().getName());
228- String cfName = Metadata.escapeId(table.getName());
229- String colName = Metadata.escapeId(column.getName());
230- return isCustomIndex()
231- ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' WITH OPTIONS = %s;",
232- name, ksName, cfName, colName, getIndexClassName(), getOptionsAsCql())
233- : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, getIndexFunction(colName));
234- }
235-
236- /**
237- * Builds a string representation of the custom index options.
238- *
239- * @return String representation of the custom index options, similar to what Cassandra stores in
240- * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
241- */
242- private String getOptionsAsCql() {
243- StringBuilder builder = new StringBuilder();
244- builder.append("{");
245- Iterator<Entry<String, String>> it = indexOptions.entrySet().iterator();
246- while (it.hasNext()) {
247- Entry<String, String> option = it.next();
248- builder.append(String.format("'%s' : '%s'", option.getKey(), option.getValue()));
249- if (it.hasNext())
250- builder.append(", ");
251- }
252- builder.append("}");
253- return builder.toString();
254- }
255-
256- /**
257- * Wraps the column name with the appropriate index function (KEYS, FULL, ENTRIES),
258- * if necessary.
259- *
260- * @return Column name wrapped with the appropriate index function.
261- */
262- private String getIndexFunction(String colName) {
263- if (isKeys())
264- return String.format("KEYS(%s)", colName);
265- else if (isFull())
266- return String.format("FULL(%s)", colName);
267- else if (isEntries())
268- return String.format("ENTRIES(%s)", colName);
269- return colName;
270- }
271-
272- private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) {
273- if (indexColumns.isEmpty())
274- return null;
275-
276- String type = indexColumns.get(INDEX_TYPE);
277- if (type == null)
278- return null;
279-
280- // Special case check for the value of the index_options column being a string with value 'null' as this
281- // column appears to be set this way (JAVA-834).
282- String indexOptionsCol = indexColumns.get(INDEX_OPTIONS);
283- if (indexOptionsCol == null || indexOptionsCol.isEmpty() || indexOptionsCol.equals("null"))
284- return new IndexMetadata(column, indexColumns.get(INDEX_NAME));
285- else {
286- Map<String, String> indexOptions = SimpleJSONParser.parseStringMap(indexOptionsCol);
287- return new IndexMetadata(column, indexColumns.get(INDEX_NAME), indexOptions);
288- }
108+ public IndexMetadata getIndex(String name) {
109+ return indexes.get(Metadata.handleId(name));
110+ }
289111
290- }
112+ /**
113+ * Returns a list containing all the indexes on this column.
114+ *
115+ * @return a list containing the metadata for the indexes on this column.
116+ */
117+ public List<IndexMetadata> getIndexes() {
118+ return new ArrayList<IndexMetadata>(indexes.values());
291119 }
292120
293121 @Override
@@ -365,8 +193,10 @@
365193 DataType dataType = CassandraTypeParser.parseOne(validatorStr, protocolVersion, codecRegistry);
366194 Raw c = new Raw(name, kind, componentIndex, dataType, reversed);
367195
196+ // secondary indexes (C* < 3.0.0)
197+ // from C* 3.0 onwards 2i are defined in a separate table
368198 for (String str : Arrays.asList(INDEX_TYPE, INDEX_NAME, INDEX_OPTIONS))
369- if (!row.isNull(str))
199+ if (row.getColumnDefinitions().contains(str) && !row.isNull(str))
370200 c.indexColumns.put(str, row.getString(str));
371201
372202 return c;
added driver-core/src/main/java/com/datastax/driver/core/IndexMetadata.java +342 −0
@@ -0,0 +1,342 @@
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.core;
17+
18+import java.util.*;
19+
20+import com.google.common.base.Function;
21+import com.google.common.base.Objects;
22+import com.google.common.collect.ImmutableMap;
23+
24+/**
25+ * An immutable representation of secondary index metadata.
26+ */
27+public class IndexMetadata {
28+
29+ public enum IndexType {
30+ KEYS,
31+ CUSTOM,
32+ COMPOSITES
33+ }
34+
35+ public enum TargetType {
36+ COLUMN, ROW
37+ }
38+
39+ public static final Function<IndexMetadata, String> INDEX_NAME = new Function<IndexMetadata, String>() {
40+ @Override
41+ public String apply(IndexMetadata input) {
42+ return input.getName();
43+ }
44+ };
45+
46+ public static final String CUSTOM_INDEX_OPTION_NAME = "class_name";
47+
48+ /**
49+ * The name of the option used to specify that the index is on the collection keys.
50+ */
51+ public static final String INDEX_KEYS_OPTION_NAME = "index_keys";
52+
53+ /**
54+ * The name of the option used to specify that the index is on the collection values.
55+ */
56+ public static final String INDEX_VALUES_OPTION_NAME = "index_values";
57+
58+ /**
59+ * The name of the option used to specify that the index is on the collection (map) entries.
60+ */
61+ public static final String INDEX_ENTRIES_OPTION_NAME = "index_keys_and_values";
62+
63+
64+ private final TableMetadata table;
65+ private final String name;
66+ private final Map<String, ColumnMetadata> columns;
67+ private final IndexType indexType;
68+ private final TargetType targetType;
69+ private final Map<String, String> options;
70+
71+ private IndexMetadata(TableMetadata table, String name, Map<String, ColumnMetadata> columns, IndexType indexType, TargetType targetType, Map<String, String> options) {
72+ this.table = table;
73+ this.name = name;
74+ this.columns = columns;
75+ this.indexType = indexType;
76+ this.targetType = targetType;
77+ this.options = options;
78+ }
79+
80+ /**
81+ * Build an IndexMetadata from a system_schema.indexes row.
82+ */
83+ static IndexMetadata fromRow(TableMetadata table, Row indexRow) {
84+ String name = indexRow.getString("index_name");
85+ Set<String> targetColumnNames = indexRow.getSet("target_columns", String.class);
86+ LinkedHashMap<String, ColumnMetadata> targetColumns = new LinkedHashMap<String, ColumnMetadata>(targetColumnNames.size());
87+ for (String targetColumnName : targetColumnNames) {
88+ targetColumns.put(targetColumnName, table.getColumn(targetColumnName));
89+ }
90+ IndexMetadata.IndexType indexType = IndexMetadata.IndexType.valueOf(indexRow.getString("index_type"));
91+ IndexMetadata.TargetType targetType = IndexMetadata.TargetType.valueOf(indexRow.getString("target_type"));
92+ Map<String, String> options = indexRow.getMap("options", String.class, String.class);
93+ return new IndexMetadata(table, name, targetColumns, indexType, targetType, options);
94+ }
95+
96+ /**
97+ * Build an IndexMetadata from a legacy layout (index information is stored
98+ * along with indexed column).
99+ */
100+ static IndexMetadata fromLegacy(ColumnMetadata column, ColumnMetadata.Raw raw) {
101+ if (raw.indexColumns.isEmpty())
102+ return null;
103+ String type = raw.indexColumns.get(ColumnMetadata.INDEX_TYPE);
104+ if (type == null)
105+ return null;
106+ String indexName = raw.indexColumns.get(ColumnMetadata.INDEX_NAME);
107+ String indexTypeStr = raw.indexColumns.get(ColumnMetadata.INDEX_TYPE);
108+ IndexType indexType = indexTypeStr == null ? null : IndexType.valueOf(indexTypeStr);
109+ // Special case check for the value of the index_options column being a string with value 'null' as this
110+ // column appears to be set this way (JAVA-834).
111+ String indexOptionsCol = raw.indexColumns.get(ColumnMetadata.INDEX_OPTIONS);
112+ ImmutableMap<String, ColumnMetadata> columns = ImmutableMap.of(column.getName(), column);
113+ Map<String, String> options;
114+ if (indexOptionsCol == null || indexOptionsCol.isEmpty() || indexOptionsCol.equals("null")) {
115+ options = ImmutableMap.of();
116+ } else {
117+ options = SimpleJSONParser.parseStringMap(indexOptionsCol);
118+ }
119+ return new IndexMetadata(column.getTable(), indexName, columns, indexType, TargetType.COLUMN, options);
120+ }
121+
122+ /**
123+ * Returns the metadata of the table this column is part of.
124+ *
125+ * @return the {@code TableMetadata} for the table this column is part of.
126+ */
127+ public TableMetadata getTable() {
128+ return table;
129+ }
130+
131+ /**
132+ * Returns the index name.
133+ *
134+ * @return the index name.
135+ */
136+ public String getName() {
137+ return name;
138+ }
139+
140+ /**
141+ * Returns metadata on a column of this index.
142+ *
143+ * @param name the name of the column to retrieve ({@code name} will be
144+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
145+ * see {@link Metadata#quote}).
146+ * @return the metadata for the column if it exists, or
147+ * {@code null} otherwise.
148+ */
149+ public ColumnMetadata getColumn(String name) {
150+ return columns.get(Metadata.handleId(name));
151+ }
152+
153+ /**
154+ * Returns a list containing all the columns of this index.
155+ *
156+ * The order of the columns in the list is consistent with
157+ * the order of the columns in the index.
158+ *
159+ * @return a list containing the metadata for the columns of this table.
160+ */
161+ public List<ColumnMetadata> getColumns() {
162+ return new ArrayList<ColumnMetadata>(columns.values());
163+ }
164+
165+ /**
166+ * Returns the index type.
167+ *
168+ * @return the index type.
169+ */
170+ public IndexType getIndexType() {
171+ return indexType;
172+ }
173+
174+ /**
175+ * Returns the index target type.
176+ * Note: for legacy indexes, this is always {@link TargetType#COLUMN}.
177+ *
178+ * @return the index target type.
179+ */
180+ public TargetType getTargetType() {
181+ return targetType;
182+ }
183+
184+ /**
185+ * Returns whether this index is a custom one.
186+ * <p>
187+ * If it is indeed a custom index, {@link #getIndexClassName} will
188+ * return the name of the class used in Cassandra to implement that
189+ * index.
190+ *
191+ * @return {@code true} if this metadata represents a custom index.
192+ */
193+ public boolean isCustomIndex() {
194+ return getIndexClassName() != null;
195+ }
196+
197+ /**
198+ * The name of the class used to implement the custom index, if it is one.
199+ *
200+ * @return the name of the class used Cassandra side to implement this
201+ * custom index if {@code isCustomIndex() == true}, {@code null} otherwise.
202+ */
203+ public String getIndexClassName() {
204+ return getOption(CUSTOM_INDEX_OPTION_NAME);
205+ }
206+
207+ /**
208+ * Return whether this index is a 'KEYS' index on a map, e.g.,
209+ * CREATE INDEX ON mytable (KEYS(mymap))
210+ *
211+ * @return {@code true} if this is a 'KEYS' index on a map.
212+ */
213+ public boolean isKeys() {
214+ return getOption(INDEX_KEYS_OPTION_NAME) != null;
215+ }
216+
217+ /**
218+ * Return whether this index is a 'VALUES' index on a map, e.g.,
219+ * CREATE INDEX ON mytable (VALUES(mymap))
220+ *
221+ * @return {@code true} if this is an 'VALUES' index on a map.
222+ */
223+ public boolean isValues() {
224+ return getOption(INDEX_VALUES_OPTION_NAME) != null;
225+ }
226+
227+ /**
228+ * Return whether this index is a 'ENTRIES' index on a map, e.g.,
229+ * CREATE INDEX ON mytable (ENTRIES(mymap))
230+ *
231+ * @return {@code true} if this is an 'ENTRIES' index on a map.
232+ */
233+ public boolean isEntries() {
234+ return getOption(INDEX_ENTRIES_OPTION_NAME) != null;
235+ }
236+
237+ /**
238+ * Return whether this index is a 'FULL' index on a frozen collection, e.g.,
239+ * CREATE INDEX ON mytable (FULL(mymap))
240+ *
241+ * @return {@code true} if this is a 'FULL' index on a frozen collection.
242+ */
243+ public boolean isFull() {
244+ /*
245+ * This check is analogous to the Cassandra counterpart
246+ * in IndexTarget.
247+ */
248+ ColumnMetadata column = columns.values().iterator().next();
249+ return
250+ !isKeys()
251+ && !isValues()
252+ && !isEntries()
253+ && column.getType() instanceof DataType.CollectionType
254+ && column.getType().isFrozen();
255+ }
256+
257+ /**
258+ * Return the value for the given option name.
259+ *
260+ * @param name Option name
261+ * @return Option value
262+ */
263+ public String getOption(String name) {
264+ return options != null ? options.get(name) : null;
265+ }
266+
267+ /**
268+ * Returns a CQL query representing this index.
269+ *
270+ * This method returns a single 'CREATE INDEX' query corresponding to
271+ * this index definition.
272+ *
273+ * @return the 'CREATE INDEX' query corresponding to this index.
274+ */
275+ public String asCQLQuery() {
276+ TableMetadata table = getTable();
277+ String ksName = Metadata.escapeId(table.getKeyspace().getName());
278+ String cfName = Metadata.escapeId(table.getName());
279+ // TODO indexes on multiple columns
280+ String colName = Metadata.escapeId(columns.keySet().iterator().next());
281+ return isCustomIndex()
282+ ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' WITH OPTIONS = %s;", name, ksName, cfName, colName, getIndexClassName(), getOptionsAsCql())
283+ : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, getIndexFunction(colName));
284+ }
285+
286+ /**
287+ * Builds a string representation of the custom index options.
288+ *
289+ * @return String representation of the custom index options, similar to what Cassandra stores in
290+ * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
291+ */
292+ private String getOptionsAsCql() {
293+ StringBuilder builder = new StringBuilder();
294+ builder.append("{");
295+ Iterator<Map.Entry<String, String>> it = options.entrySet().iterator();
296+ while (it.hasNext()) {
297+ Map.Entry<String, String> option = it.next();
298+ builder.append(String.format("'%s' : '%s'", option.getKey(), option.getValue()));
299+ if (it.hasNext())
300+ builder.append(", ");
301+ }
302+ builder.append("}");
303+ return builder.toString();
304+ }
305+
306+ /**
307+ * Wraps the column name with the appropriate index function (KEYS, FULL, ENTRIES),
308+ * if necessary.
309+ *
310+ * @return Column name wrapped with the appropriate index function.
311+ */
312+ private String getIndexFunction(String colName) {
313+ if (isKeys())
314+ return String.format("KEYS(%s)", colName);
315+ else if (isFull())
316+ return String.format("FULL(%s)", colName);
317+ else if (isEntries())
318+ return String.format("ENTRIES(%s)", colName);
319+ return colName;
320+ }
321+
322+ public int hashCode() {
323+ return Objects.hashCode(name, columns, indexType, targetType, options);
324+ }
325+
326+ public boolean equals(Object obj) {
327+ if (obj == this)
328+ return true;
329+
330+ if (!(obj instanceof IndexMetadata))
331+ return false;
332+
333+ IndexMetadata other = (IndexMetadata)obj;
334+
335+ return Objects.equal(name, other.name)
336+ && Objects.equal(columns, other.columns)
337+ && Objects.equal(indexType, other.indexType)
338+ && Objects.equal(targetType, other.targetType)
339+ && Objects.equal(options, other.options);
340+ }
341+
342+}
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +37 −7
@@ -18,6 +18,8 @@
1818 import java.util.*;
1919 import java.util.concurrent.ExecutionException;
2020
21+import com.google.common.collect.Lists;
22+import com.google.common.collect.Maps;
2123 import org.slf4j.Logger;
2224 import org.slf4j.LoggerFactory;
2325
@@ -117,7 +119,7 @@
117119 buildUserTypes(ksm, udtDefs.get(ksName), protocolVersion, codecRegistry);
118120 }
119121 if (cfDefs.containsKey(ksName)) {
120- buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
122+ buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), null, cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
121123 }
122124 if (functionDefs.containsKey(ksName)) {
123125 buildFunctionMetadata(ksm, functionDefs.get(ksName), protocolVersion, codecRegistry);
@@ -153,7 +155,7 @@
153155 switch (targetType) {
154156 case TABLE:
155157 if (cfDefs.containsKey(targetKeyspace))
156- buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
158+ buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), null, cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
157159 break;
158160 case TYPE:
159161 if (udtDefs.containsKey(targetKeyspace))
@@ -194,6 +196,7 @@
194196 private static final String SELECT_USERTYPES = "SELECT * FROM system_schema.types";
195197 private static final String SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions";
196198 private static final String SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates";
199+ private static final String SELECT_INDEXES = "SELECT * FROM system_schema.indexes";
197200
198201 private static final String TABLE_NAME = "table_name";
199202
@@ -225,7 +228,8 @@
225228 cfFuture = null,
226229 colsFuture = null,
227230 functionsFuture = null,
228- aggregatesFuture = null;
231+ aggregatesFuture = null,
232+ indexesFuture = null;
229233
230234 if (isSchemaOrKeyspace)
231235 ksFuture = queryAsync(SELECT_KEYSPACES + whereClause, connection, protocolVersion);
@@ -236,6 +240,7 @@
236240 if (isSchemaOrKeyspace || targetType == TABLE) {
237241 cfFuture = queryAsync(SELECT_TABLES + whereClause, connection, protocolVersion);
238242 colsFuture = queryAsync(SELECT_COLUMNS + whereClause, connection, protocolVersion);
243+ indexesFuture = queryAsync(SELECT_INDEXES + whereClause, connection, protocolVersion);
239244 }
240245
241246 if ((isSchemaOrKeyspace || targetType == FUNCTION))
@@ -250,6 +255,7 @@
250255 Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
251256 Map<String, List<Row>> functionDefs = groupByKeyspace(get(functionsFuture));
252257 Map<String, List<Row>> aggregateDefs = groupByKeyspace(get(aggregatesFuture));
258+ Map<String, Map<String, List<Row>>> indexDefs = groupByKeyspaceAndCf(get(indexesFuture), TABLE_NAME);
253259
254260 metadata.lock.lock();
255261 try {
@@ -264,7 +270,7 @@
264270 buildUserTypes(ksm, udtDefs.get(ksName), protocolVersion, codecRegistry);
265271 }
266272 if (cfDefs.containsKey(ksName)) {
267- buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
273+ buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), indexDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
268274 }
269275 if (functionDefs.containsKey(ksName)) {
270276 buildFunctionMetadata(ksm, functionDefs.get(ksName), protocolVersion, codecRegistry);
@@ -300,7 +306,7 @@
300306 switch (targetType) {
301307 case TABLE:
302308 if (cfDefs.containsKey(targetKeyspace))
303- buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
309+ buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), indexDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
304310 break;
305311 case TYPE:
306312 if (udtDefs.containsKey(targetKeyspace))
@@ -324,7 +330,7 @@
324330 }
325331 };
326332
327- static void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
333+ static void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, Map<String, List<Row>> ksIndexes, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
328334 for (Row cfRow : cfRows) {
329335 String cfName = cfRow.getString(tableName);
330336 try {
@@ -348,7 +354,8 @@
348354 cols = Collections.emptyMap();
349355 }
350356 }
351- ksm.add(TableMetadata.build(ksm, cfRow, cols, tableName, cassandraVersion, protocolVersion, codecRegistry));
357+ List<Row> cfIndexes = (ksIndexes == null) ? null : ksIndexes.get(cfName);
358+ ksm.add(TableMetadata.build(ksm, cfRow, cols, cfIndexes, tableName, cassandraVersion, protocolVersion, codecRegistry));
352359 } catch (RuntimeException e) {
353360 // See ControlConnection#refreshSchema for why we'd rather not probably this further
354361 logger.error(String.format("Error parsing schema for table %s.%s: "
@@ -390,6 +397,29 @@
390397 return result;
391398 }
392399
400+ static Map<String, Map<String, List<Row>>> groupByKeyspaceAndCf(ResultSet rs, String tableName) {
401+ if (rs == null)
402+ return Collections.emptyMap();
403+
404+ Map<String, Map<String, List<Row>>> result = Maps.newHashMap();
405+ for (Row row : rs) {
406+ String ksName = row.getString(KeyspaceMetadata.KS_NAME);
407+ String cfName = row.getString(tableName);
408+ Map<String, List<Row>> rowsByCf = result.get(ksName);
409+ if (rowsByCf == null) {
410+ rowsByCf = Maps.newHashMap();
411+ result.put(ksName, rowsByCf);
412+ }
413+ List<Row> l = rowsByCf.get(cfName);
414+ if (l == null) {
415+ l = Lists.newArrayList();
416+ rowsByCf.put(cfName, l);
417+ }
418+ l.add(row);
419+ }
420+ return result;
421+ }
422+
393423 static Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndCf(ResultSet rs, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
394424 if (rs == null)
395425 return Collections.emptyMap();
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +85 −22
@@ -64,9 +64,11 @@
6464 private final List<ColumnMetadata> partitionKey;
6565 private final List<ColumnMetadata> clusteringColumns;
6666 private final Map<String, ColumnMetadata> columns;
67+ private final Map<String, IndexMetadata> indexes;
6768 private final Options options;
6869 private final List<Order> clusteringOrder;
6970
71+
7072 private final VersionNumber cassandraVersion;
7173
7274 /**
@@ -90,7 +92,8 @@
9092 UUID id,
9193 List<ColumnMetadata> partitionKey,
9294 List<ColumnMetadata> clusteringColumns,
93- LinkedHashMap<String, ColumnMetadata> columns,
95+ Map<String, ColumnMetadata> columns,
96+ Map<String, IndexMetadata> indexes,
9497 Options options,
9598 List<Order> clusteringOrder,
9699 VersionNumber cassandraVersion) {
@@ -100,27 +103,28 @@
100103 this.partitionKey = partitionKey;
101104 this.clusteringColumns = clusteringColumns;
102105 this.columns = columns;
106+ this.indexes = indexes;
103107 this.options = options;
104108 this.clusteringOrder = clusteringOrder;
105109 this.cassandraVersion = cassandraVersion;
106110 }
107111
108- static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, String nameColumn, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
112+ static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, List<Row> indexRows, String nameColumn, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
109113
110114 String name = row.getString(nameColumn);
111115
112116 UUID id = null;
113117
114- if(cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)
118+ if (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)
115119 id = row.getUUID(CF_ID_V2);
116- else if(cassandraVersion.getMajor() > 2)
120+ else if (cassandraVersion.getMajor() > 2)
117121 id = row.getUUID(CF_ID_V3);
118122
119123 CassandraTypeParser.ParseResult comparator = null;
120124 CassandraTypeParser.ParseResult keyValidator = null;
121125 List<String> columnAliases = null;
122126
123- if(cassandraVersion.getMajor() <= 2) {
127+ if (cassandraVersion.getMajor() <= 2) {
124128 comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
125129 keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
126130 columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
@@ -133,17 +137,17 @@
133137
134138 boolean isDense;
135139 boolean isCompact;
136- if(cassandraVersion.getMajor() > 2) {
140+ if (cassandraVersion.getMajor() > 2) {
137141 Set<String> flags = row.getSet(FLAGS, String.class);
138142 isDense = flags.contains(DENSE);
139143 boolean isSuper = flags.contains(SUPER);
140144 boolean isCompound = flags.contains(COMPOUND);
141145 isCompact = isSuper || isDense || !isCompound;
142146 boolean isStaticCompact = !isSuper && !isDense && !isCompound;
143- if(isStaticCompact) {
147+ if (isStaticCompact) {
144148 rawCols = pruneStaticCompactTableColumns(rawCols);
145149 }
146- if(isDense) {
150+ if (isDense) {
147151 rawCols = pruneDenseTableColumnsV3(rawCols);
148152 }
149153 clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
@@ -151,7 +155,7 @@
151155 assert comparator != null;
152156 clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
153157 isDense = clusteringSize != comparator.types.size() - 1;
154- if(isDense) {
158+ if (isDense) {
155159 rawCols = pruneDenseTableColumnsV2(rawCols);
156160 }
157161 isCompact = isDense || !comparator.isComposite;
@@ -163,6 +167,7 @@
163167
164168 // We use a linked hashmap because we will keep this in the order of a 'SELECT * FROM ...'.
165169 LinkedHashMap<String, ColumnMetadata> columns = new LinkedHashMap<String, ColumnMetadata>();
170+ LinkedHashMap<String, IndexMetadata> indexes = new LinkedHashMap<String, IndexMetadata>();
166171
167172 Options options = null;
168173 try {
@@ -171,11 +176,11 @@
171176 // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
172177 // that tends to change often in Cassandra, it's worth special casing this.
173178 logger.error(String.format("Error parsing schema options for table %s.%s: "
174- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
175- ksm.getName(), name, ksm.getName(), name), e);
179+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
180+ ksm.getName(), name, ksm.getName(), name), e);
176181 }
177182
178- TableMetadata tm = new TableMetadata(ksm, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
183+ TableMetadata tm = new TableMetadata(ksm, name, id, partitionKey, clusteringColumns, columns, indexes, options, clusteringOrder, cassandraVersion);
179184
180185 // We use this temporary set just so non PK columns are added in lexicographical order, which is the one of a
181186 // 'SELECT * FROM ...'
@@ -190,8 +195,8 @@
190195 // In C* 1.2, only the REGULAR columns are in the columns schema table, so we need to add the names from
191196 // the aliases (and make sure we handle default aliases).
192197 List<String> keyAliases = row.getString(KEY_ALIASES) == null
193- ? Collections.<String>emptyList()
194- : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
198+ ? Collections.<String>emptyList()
199+ : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
195200 for (int i = 0; i < partitionKey.size(); i++) {
196201 String alias = keyAliases.size() > i ? keyAliases.get(i) : (i == 0 ? DEFAULT_KEY_ALIAS : DEFAULT_KEY_ALIAS + (i + 1));
197202 partitionKey.set(i, ColumnMetadata.forAlias(tm, alias, keyValidator.types.get(i)));
@@ -207,13 +212,15 @@
207212 if (isDense) {
208213 String alias = row.isNull(VALUE_ALIAS) ? DEFAULT_VALUE_ALIAS : row.getString(VALUE_ALIAS);
209214 // ...unless the table does not have any regular column, only primary key columns (JAVA-873)
210- if(!alias.isEmpty()) {
215+ if (!alias.isEmpty()) {
211216 DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
212217 otherColumns.add(ColumnMetadata.forAlias(tm, alias, type));
213218 }
214219 }
215220 }
216221
222+ Map<ColumnMetadata, Set<IndexMetadata>> indexedColumns = new LinkedHashMap<ColumnMetadata, Set<IndexMetadata>>();
223+
217224 for (ColumnMetadata.Raw rawCol : rawCols.values()) {
218225 ColumnMetadata col = ColumnMetadata.fromRaw(tm, rawCol);
219226 switch (rawCol.kind) {
@@ -228,8 +235,15 @@
228235 otherColumns.add(col);
229236 break;
230237 }
238+ // create legacy secondary indexes (C* < 3.0)
239+ IndexMetadata index = IndexMetadata.fromLegacy(col, rawCol);
240+ if(index != null) {
241+ indexes.put(index.getName(), index);
242+ addIndexToColumn(index, col, indexedColumns);
243+ }
231244 }
232245
246+
233247 for (ColumnMetadata c : partitionKey)
234248 columns.put(c.getName(), c);
235249 for (ColumnMetadata c : clusteringColumns)
@@ -237,9 +251,40 @@
237251 for (ColumnMetadata c : otherColumns)
238252 columns.put(c.getName(), c);
239253
254+ // create secondary indexes (C* >= 3.0)
255+ if (indexRows != null)
256+ for (Row indexRow : indexRows) {
257+ IndexMetadata index = IndexMetadata.fromRow(tm, indexRow);
258+ indexes.put(index.getName(), index);
259+ // update the many-to-many relationship between indexes and columns
260+ for (ColumnMetadata column : index.getColumns()) {
261+ addIndexToColumn(index, column, indexedColumns);
262+ }
263+ }
264+
265+ // update indexed columns
266+ for (Map.Entry<ColumnMetadata, Set<IndexMetadata>> entry : indexedColumns.entrySet()) {
267+ ColumnMetadata column = entry.getKey();
268+ for (IndexMetadata index : entry.getValue()) {
269+ // update the "reverse" side of the many-to-many relationship between indexes and columns
270+ column.indexes.put(index.getName(), index);
271+ }
272+ }
240273 return tm;
241274 }
242275
276+ /**
277+ * Associate the given index with the given column and store it in the given map.
278+ */
279+ private static void addIndexToColumn(IndexMetadata index, ColumnMetadata column, Map<ColumnMetadata, Set<IndexMetadata>> indexedColumns) {
280+ Set<IndexMetadata> indexes = indexedColumns.get(column);
281+ if(indexes == null) {
282+ indexes = new LinkedHashSet<IndexMetadata>();
283+ indexedColumns.put(column, indexes);
284+ }
285+ indexes.add(index);
286+ }
287+
243288 /**
244289 * Upon migration from thrift to CQL, we internally create a pair of surrogate clustering/regular columns
245290 * for compact static tables. These columns shouldn't be exposed to the user but are currently returned by C*.
@@ -372,7 +417,7 @@
372417 * @param name the name of the column to retrieve ({@code name} will be
373418 * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
374419 * see {@link Metadata#quote}).
375- * @return the metadata for the {@code name} column if it exists, or
420+ * @return the metadata for the column if it exists, or
376421 * {@code null} otherwise.
377422 */
378423 public ColumnMetadata getColumn(String name) {
@@ -432,6 +477,28 @@
432477 return Collections.unmodifiableList(clusteringColumns);
433478 }
434479
480+ /**
481+ * Returns metadata on a index of this table.
482+ *
483+ * @param name the name of the index to retrieve ({@code name} will be
484+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
485+ * see {@link Metadata#quote}).
486+ * @return the metadata for the {@code name} index if it exists, or
487+ * {@code null} otherwise.
488+ */
489+ public IndexMetadata getIndex(String name) {
490+ return indexes.get(Metadata.handleId(name));
491+ }
492+
493+ /**
494+ * Returns a list containing all the indexes of this table.
495+ *
496+ * @return a list containing the metadata for the indexes of this table.
497+ */
498+ public List<IndexMetadata> getIndexes() {
499+ return new ArrayList<IndexMetadata>(indexes.values());
500+ }
501+
435502 /**
436503 * Returns the clustering order for this table.
437504 * <p>
@@ -466,7 +533,7 @@
466533 * table and the index on it.
467534 * <p>
468535 * In other words, this method returns the queries that would allow you to
469- * recreate the schema of this table, along with the index defined on
536+ * recreate the schema of this table, along with the indexes defined on
470537 * columns of this table.
471538 * <p>
472539 * Note that the returned String is formatted to be human readable (for
@@ -480,11 +547,7 @@
480547
481548 sb.append(asCQLQuery(true));
482549
483- for (ColumnMetadata column : columns.values()) {
484- ColumnMetadata.IndexMetadata index = column.getIndex();
485- if (index == null)
486- continue;
487-
550+ for (IndexMetadata index : indexes.values()) {
488551 sb.append('\n').append(index.asCQLQuery());
489552 }
490553 return sb.toString();
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −6
@@ -15,8 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
19-
2018 /**
2119 * Augment AssertJ with custom assertions for the Java driver.
2220 */
@@ -37,10 +35,6 @@
3735 return new DataTypeAssert(type);
3836 }
3937
40- public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) {
41- return new IndexMetadataAssert(indexMetadata);
42- }
43-
4438 public static LocalDateAssert assertThat(LocalDate localDate) {
4539 return new LocalDateAssert(localDate);
4640 }
@@ -53,6 +47,10 @@
5347 return new ColumnMetadataAssert(column);
5448 }
5549
50+ public static IndexMetadataAssert assertThat(IndexMetadata index) {
51+ return new IndexMetadataAssert(index);
52+ }
53+
5654 public static TypeCodecAssert assertThat(TypeCodec codec) {
5755 return new TypeCodecAssert(codec);
5856 }
modified driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java +10 −0
@@ -70,4 +70,14 @@
7070 return this;
7171 }
7272
73+ public ColumnMetadataAssert hasIndex(IndexMetadata index) {
74+ assertThat(actual.getIndex(index.getName())).isEqualTo(index);
75+ return this;
76+ }
77+
78+ public ColumnMetadataAssert hasSingleIndex(IndexMetadata index) {
79+ assertThat(actual.getIndexes()).containsOnly(index);
80+ return this;
81+ }
82+
7383 }
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +5 −8
@@ -180,17 +180,14 @@
180180 */
181181 @Test(groups = "short")
182182 public void should_echo_custom_payload_when_paginating() throws Exception {
183- session.execute("INSERT INTO t1 (c1) VALUES (1)");
184- session.execute("INSERT INTO t1 (c1) VALUES (2)");
185- Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 IN (1,2)");
183+ session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'a')");
184+ session.execute("INSERT INTO t1 (c1, c2) VALUES (1, 'b')");
185+ Statement statement = session.newSimpleStatement("SELECT c2 FROM t1 where c1 = 1");
186186 statement.setFetchSize(1);
187187 statement.setOutgoingPayload(payload1);
188188 ResultSet rows = session.execute(statement);
189189 rows.all();
190- for (ExecutionInfo info : rows.getAllExecutionInfo()) {
191- Map<String, ByteBuffer> actual = info.getIncomingPayload();
192- assertThat(actual).isEqualTo(payload1);
193- }
190+ assertThat(rows.getAllExecutionInfo()).extracting("incomingPayload").containsOnly(payload1);
194191 }
195192
196193 // TODO retries, spec execs
@@ -298,7 +295,7 @@
298295
299296 @Override
300297 protected Collection<String> getTableDefinitions() {
301- return Collections.singletonList("CREATE TABLE t1 (c1 int PRIMARY KEY, c2 text)");
298+ return Collections.singletonList("CREATE TABLE t1 (c1 int, c2 text, PRIMARY KEY (c1, c2))");
302299 }
303300
304301 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java +11 −4
@@ -15,11 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static org.assertj.core.api.Assertions.assertThat;
19-
2018 import org.assertj.core.api.AbstractAssert;
2119
22-import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
20+import static org.assertj.core.api.Assertions.assertThat;
2321
2422 public class IndexMetadataAssert extends AbstractAssert<IndexMetadataAssert, IndexMetadata> {
2523
@@ -81,5 +79,14 @@
8179 assertThat(actual.isCustomIndex()).isFalse();
8280 return this;
8381 }
84-
82+
83+ public IndexMetadataAssert hasColumn(ColumnMetadata column) {
84+ assertThat(actual.getColumn(column.getName())).isEqualTo(column);
85+ return this;
86+ }
87+
88+ public IndexMetadataAssert hasSingleColumn(ColumnMetadata column) {
89+ assertThat(actual.getColumns()).containsOnly(column);
90+ return this;
91+ }
8592 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +102 −82
@@ -32,23 +32,22 @@
3232 import static com.datastax.driver.core.DataType.cint;
3333 import static com.datastax.driver.core.DataType.text;
3434
35-@CassandraVersion(
36- major = 1.2)
35+@CassandraVersion(major = 1.2)
3736 public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3837
3938 /**
4039 * Column definitions for schema_columns table.
4140 */
42- private static final ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[] {
43- definition(COLUMN_NAME, text()),
44- definition(COMPONENT_INDEX, cint()),
45- definition(KIND, text()),
46- definition(INDEX_NAME, text()),
47- definition(INDEX_TYPE, text()),
48- definition(VALIDATOR, text()),
49- definition(INDEX_OPTIONS, text())
41+ private static final ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
42+ definition(COLUMN_NAME, text()),
43+ definition(COMPONENT_INDEX, cint()),
44+ definition(KIND, text()),
45+ definition(INDEX_NAME, text()),
46+ definition(INDEX_TYPE, text()),
47+ definition(VALIDATOR, text()),
48+ definition(INDEX_OPTIONS, text())
5049 });
51-
50+
5251 static {
5352 defs.setCodecRegistry(new CodecRegistry());
5453 }
@@ -64,131 +63,150 @@
6463 +
6564 // Frozen collections was introduced only in C* 2.1.3
6665 (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
67- ?
66+ ?
6867 ", map_full frozen<map<text, int>>,"
69- + "set_full frozen<set<text>>,"
70- + "list_full frozen<list<text>>);"
71- :
68+ + "set_full frozen<set<text>>,"
69+ + "list_full frozen<list<text>>);"
70+ :
7271 ")");
7372 return ImmutableList.of(createTable);
7473 }
75-
76- @Test(
77- groups = "short")
74+
75+ @Test(groups = "short")
7876 public void should_not_flag_text_column_index_type() {
7977 String createValuesIndex = String.format("CREATE INDEX text_column_index ON %s.indexing (text_column);", keyspace);
8078 session.execute(createValuesIndex);
81- IndexMetadata index = getIndexForColumn("text_column");
79+ ColumnMetadata column = getColumn("text_column");
80+ IndexMetadata index = getIndex("text_column_index");
8281 assertThat(index).hasName("text_column_index")
8382 .isNotKeys()
8483 .isNotFull()
8584 .isNotEntries()
8685 .isNotCustomIndex()
86+ .hasSingleColumn(getColumn("text_column"))
8787 .asCqlQuery(createValuesIndex);
88+ assertThat(index).isSameAs(column.getIndex("text_column_index"));
89+ assertThat(column).hasSingleIndex(index);
90+ assertThat(column).isSameAs(index.getColumn("text_column"));
8891 }
8992
90- @Test(
91- groups = "short")
92- @CassandraVersion(
93- major = 2.1)
93+ @Test(groups = "short")
94+ @CassandraVersion(major = 2.1)
9495 public void should_not_flag_map_index_type() {
9596 String createValuesIndex = String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
9697 session.execute(createValuesIndex);
97- IndexMetadata index = getIndexForColumn("map_values");
98+ ColumnMetadata column = getColumn("map_values");
99+ IndexMetadata index = getIndex("map_values_index");
98100 assertThat(index).hasName("map_values_index")
99101 .isNotKeys()
100102 .isNotFull()
101103 .isNotEntries()
102104 .isNotCustomIndex()
105+ .hasSingleColumn(getColumn("map_values"))
103106 .asCqlQuery(createValuesIndex);
107+ assertThat(index).isSameAs(column.getIndex("map_values_index"));
108+ assertThat(column).hasSingleIndex(index);
109+ assertThat(column).isSameAs(index.getColumn("map_values"));
104110 }
105111
106- @Test(
107- groups = "short")
108- @CassandraVersion(
109- major = 2.1)
112+ @Test(groups = "short")
113+ @CassandraVersion(major = 2.1)
110114 public void should_flag_map_index_type_as_keys() {
111115 String createKeysIndex = String.format("CREATE INDEX map_keys_index ON %s.indexing (KEYS(map_keys));", keyspace);
112116 session.execute(createKeysIndex);
113- IndexMetadata index = getIndexForColumn("map_keys");
117+ ColumnMetadata column = getColumn("map_keys");
118+ IndexMetadata index = getIndex("map_keys_index");
114119 assertThat(index).hasName("map_keys_index")
115120 .isKeys()
116121 .isNotFull()
117122 .isNotEntries()
118123 .isNotCustomIndex()
124+ .hasSingleColumn(getColumn("map_keys"))
119125 .asCqlQuery(createKeysIndex);
126+ assertThat(index).isSameAs(column.getIndex("map_keys_index"));
127+ assertThat(column).hasSingleIndex(index);
128+ assertThat(column).isSameAs(index.getColumn("map_keys"));
120129 }
121130
122- @Test(
123- groups = "short")
124- @CassandraVersion(
125- major = 2.1,
126- minor = 3)
131+ @Test(groups = "short")
132+ @CassandraVersion(major = 2.1, minor = 3)
127133 public void should_flag_map_index_type_as_full() {
128134 String createFullIndex = String.format("CREATE INDEX map_full_index ON %s.indexing (FULL(map_full));", keyspace);
129135 session.execute(createFullIndex);
130- IndexMetadata index = getIndexForColumn("map_full");
136+ ColumnMetadata column = getColumn("map_full");
137+ IndexMetadata index = getIndex("map_full_index");
131138 assertThat(index).hasName("map_full_index")
132139 .isNotKeys()
133140 .isFull()
134141 .isNotEntries()
135142 .isNotCustomIndex()
143+ .hasSingleColumn(getColumn("map_full"))
136144 .asCqlQuery(createFullIndex);
145+ assertThat(index).isSameAs(column.getIndex("map_full_index"));
146+ assertThat(column).hasSingleIndex(index);
147+ assertThat(column).isSameAs(index.getColumn("map_full"));
137148 }
138149
139- @Test(
140- groups = "short")
141- @CassandraVersion(
142- major = 2.1,
143- minor = 3)
150+ @Test(groups = "short")
151+ @CassandraVersion(major = 2.1, minor = 3)
144152 public void should_flag_set_index_type_as_full() {
145153 String createFullIndex = String.format("CREATE INDEX set_full_index ON %s.indexing (FULL(set_full));", keyspace);
146154 session.execute(createFullIndex);
147- IndexMetadata index = getIndexForColumn("set_full");
155+ ColumnMetadata column = getColumn("set_full");
156+ IndexMetadata index = getIndex("set_full_index");
148157 assertThat(index).hasName("set_full_index")
149158 .isNotKeys()
150159 .isFull()
151160 .isNotEntries()
152161 .isNotCustomIndex()
162+ .hasSingleColumn(getColumn("set_full"))
153163 .asCqlQuery(createFullIndex);
164+ assertThat(index).isSameAs(column.getIndex("set_full_index"));
165+ assertThat(column).hasSingleIndex(index);
166+ assertThat(column).isSameAs(index.getColumn("set_full"));
154167 }
155168
156- @Test(
157- groups = "short")
158- @CassandraVersion(
159- major = 2.1,
160- minor = 3)
169+ @Test(groups = "short")
170+ @CassandraVersion(major = 2.1, minor = 3)
161171 public void should_flag_list_index_type_as_full() {
162172 String createFullIndex = String.format("CREATE INDEX list_full_index ON %s.indexing (FULL(list_full));", keyspace);
163173 session.execute(createFullIndex);
164- IndexMetadata index = getIndexForColumn("list_full");
174+ ColumnMetadata column = getColumn("list_full");
175+ IndexMetadata index = getIndex("list_full_index");
165176 assertThat(index).hasName("list_full_index")
166177 .isNotKeys()
167178 .isFull()
168179 .isNotEntries()
169180 .isNotCustomIndex()
181+ .hasSingleColumn(getColumn("list_full"))
170182 .asCqlQuery(createFullIndex);
183+ assertThat(index).isSameAs(column.getIndex("list_full_index"));
184+ assertThat(column).hasSingleIndex(index);
185+ assertThat(column).isSameAs(index.getColumn("list_full"));
171186 }
172187
173- @Test(
174- groups = "short")
175- @CassandraVersion(
176- major = 3.0)
188+ @Test(groups = "short")
189+ @CassandraVersion(major = 2.2)
177190 public void should_flag_map_index_type_as_entries() {
178191 String createEntriesIndex = String.format("CREATE INDEX map_entries_index ON %s.indexing (ENTRIES(map_entries));", keyspace);
179192 session.execute(createEntriesIndex);
180- IndexMetadata index = getIndexForColumn("map_entries");
193+ ColumnMetadata column = getColumn("map_entries");
194+ IndexMetadata index = getIndex("map_entries_index");
181195 assertThat(index).hasName("map_entries_index")
182196 .isNotKeys()
183197 .isNotFull()
184198 .isEntries()
185199 .isNotCustomIndex()
200+ .hasSingleColumn(getColumn("map_entries"))
186201 .asCqlQuery(createEntriesIndex);
202+ assertThat(index).isSameAs(column.getIndex("map_entries_index"));
203+ assertThat(column).hasSingleIndex(index);
204+ assertThat(column).isSameAs(index.getColumn("map_entries"));
187205 }
188206
189207 @Test(
190208 groups = "short",
191- description = "This test case builds a ColumnMetadata object programatically to test custom indices,"
209+ description = "This test case builds a ColumnMetadata object programmatically to test custom indices,"
192210 + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
193211 public void should_parse_custom_index_options() {
194212 TableMetadata table = getTable("indexing");
@@ -200,15 +218,19 @@
200218 wrap("CUSTOM"), // index type
201219 wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
202220 wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
203- );
204- Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
205- ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1"), ProtocolVersion.V3, new CodecRegistry()));
206- IndexMetadata index = column.getIndex();
221+ );
222+ Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), data);
223+ Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"),
224+ cluster.getConfiguration().getProtocolOptions().getProtocolVersion(),
225+ cluster.getConfiguration().getCodecRegistry());
226+ ColumnMetadata column = ColumnMetadata.fromRaw(table, raw);
227+ IndexMetadata index = IndexMetadata.fromLegacy(column, raw);
207228 assertThat(index).hasName("custom_index")
208229 .isNotKeys()
209230 .isNotFull()
210231 .isNotEntries()
211232 .isCustomIndex()
233+ .hasSingleColumn(column)
212234 .hasOption("foo", "bar")
213235 .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
214236 + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar', 'class_name' : 'dummy.DummyIndex'};", keyspace));
@@ -226,32 +248,30 @@
226248 @Test(groups = "short")
227249 public void should_parse_with_null_string_index_options() {
228250 TableMetadata table = getTable("indexing");
229-
230251 List<ByteBuffer> data = ImmutableList.of(
231- wrap("b@706172656e745f70617468"), // column name 'parent_path'
232- ByteBuffer.allocate(0), // component index (null)
233- wrap("regular"), // kind
234- wrap("cfs_archive_parent_path"), // index name
235- wrap("KEYS"), // index type
236- wrap("org.apache.cassandra.db.marshal.BytesType"), // validator
237- wrap("null") // index options
252+ wrap("b@706172656e745f70617468"), // column name 'parent_path'
253+ ByteBuffer.allocate(0), // component index (null)
254+ wrap("regular"), // kind
255+ wrap("cfs_archive_parent_path"), // index name
256+ wrap("KEYS"), // index type
257+ wrap("org.apache.cassandra.db.marshal.BytesType"), // validator
258+ wrap("null") // index options
238259 );
239- Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
240- ColumnMetadata column = ColumnMetadata.fromRaw(table,
241- Raw.fromRow(row, VersionNumber.parse("2.1"),
242- cluster.getConfiguration().getProtocolOptions().getProtocolVersion(),
243- cluster.getConfiguration().getCodecRegistry()));
244- IndexMetadata index = column.getIndex();
245-
260+ Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), data);
261+ Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"),
262+ cluster.getConfiguration().getProtocolOptions().getProtocolVersion(),
263+ cluster.getConfiguration().getCodecRegistry());
264+ ColumnMetadata column = ColumnMetadata.fromRaw(table, raw);
265+ IndexMetadata index = IndexMetadata.fromLegacy(column, raw);
246266 assertThat(index).hasName("cfs_archive_parent_path")
247- .isNotKeys() // While the index type is KEYS, since it lacks index_options it does not considered.
248- .isNotFull()
249- .isNotEntries()
250- .isNotCustomIndex()
251- .asCqlQuery(String.format("CREATE INDEX cfs_archive_parent_path ON %s.indexing (\"b@706172656e745f70617468\");", keyspace));
267+ .isNotKeys() // While the index type is KEYS, since it lacks index_options it does not considered.
268+ .isNotFull()
269+ .isNotEntries()
270+ .isNotCustomIndex()
271+ .hasSingleColumn(column)
272+ .asCqlQuery(String.format("CREATE INDEX cfs_archive_parent_path ON %s.indexing (\"b@706172656e745f70617468\");", keyspace));
252273 }
253274
254-
255275 private static ColumnDefinitions.Definition definition(String name, DataType type) {
256276 return new ColumnDefinitions.Definition("ks", "table", name, type);
257277 }
@@ -264,14 +284,14 @@
264284 return ByteBuffer.wrap(Ints.toByteArray(number));
265285 }
266286
267- private IndexMetadata getIndexForColumn(String columnName) {
268- return getColumn(columnName).getIndex();
269- }
270-
271287 private ColumnMetadata getColumn(String name) {
272288 return getTable("indexing").getColumn(name);
273289 }
274290
291+ private IndexMetadata getIndex(String name) {
292+ return getTable("indexing").getIndex(name);
293+ }
294+
275295 private TableMetadata getTable(String name) {
276296 return cluster.getMetadata().getKeyspace(keyspace).getTable(name);
277297 }
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +26 −1
@@ -18,6 +18,7 @@
1818 import java.util.Collection;
1919 import java.util.Collections;
2020
21+import org.testng.SkipException;
2122 import org.testng.annotations.Test;
2223
2324 import static org.assertj.core.api.Assertions.entry;
@@ -172,6 +173,12 @@
172173
173174 @Test(groups = "short")
174175 public void should_parse_table_options() {
176+ VersionNumber version = TestUtils.findHost(cluster, 1).getCassandraVersion();
177+ if (version.getMajor() > 2) {
178+ // TODO adapt test for C* 3.0
179+ throw new SkipException("Needs adjustments to work with Cassandra 3.0");
180+ }
181+
175182 // given
176183 String cql = String.format("CREATE TABLE %s.with_options (\n"
177184 + " k text,\n"
@@ -200,7 +207,6 @@
200207 assertThat(table.getColumns().get(2)).isNotNull().hasName("c2").isClusteringColumn().hasClusteringOrder(ASC).hasType(cint());
201208 assertThat(table.getColumns().get(3)).isNotNull().hasName("i").isRegularColumn().hasType(cint());
202209 assertThat(table);
203- VersionNumber version = TestUtils.findHost(cluster, 1).getCassandraVersion();
204210
205211 // Cassandra 3.0 +
206212 if (version.getMajor() > 2) {
@@ -381,4 +387,23 @@
381387 return Collections.emptyList();
382388 }
383389
390+ @Test(groups = "short")
391+ public void should_not_mix_indexes_from_different_tables() {
392+ String[] statements = {
393+ "CREATE TABLE test_ab (a int PRIMARY KEY, b int);",
394+ "CREATE INDEX test_b on test_ab (b);",
395+ "CREATE TABLE test_cd (c int PRIMARY KEY, d int);",
396+ "CREATE INDEX test_d on test_cd (d);",
397+ };
398+ for (String statement: statements)
399+ session.execute(statement);
400+
401+ TableMetadata table_ab = cluster.getMetadata().getKeyspace(keyspace).getTable("test_ab");
402+ TableMetadata table_cd = cluster.getMetadata().getKeyspace(keyspace).getTable("test_cd");
403+
404+ assertThat(table_ab.getIndexes().size()).isEqualTo(1);
405+ assertThat(table_ab.getIndexes().get(0).getName()).isEqualTo("test_b");
406+ assertThat(table_cd.getIndexes().size()).isEqualTo(1);
407+ assertThat(table_cd.getIndexes().get(0).getName()).isEqualTo("test_d");
408+ }
384409 }
modified pom.xml +1 −1
@@ -43,7 +43,7 @@
4343
4444 <properties>
4545 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
46- <cassandra.version>3.0.0-alpha1</cassandra.version>
46+ <cassandra.version>3.0.0-beta1</cassandra.version>
4747 <java.version>1.6</java.version>
4848 <log4j.version>1.2.17</log4j.version>
4949 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>