Elffuss BraidHub

kikocis/java-driver public

JAVA-825: Parse materialized views metadata.
Changeset3989e18ceb14f4fdf380862bb925e21a8cb2fca945fdf06534c09bd409dd9730
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-09-15 20:58 +02:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-09-15 20:58 +02:00
Parents99740bf2fccd

Browse the files at this changeset

14 files changed

modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +9 −8
@@ -37,7 +37,7 @@
3737 static final String INDEX_OPTIONS = "index_options";
3838 static final String INDEX_NAME = "index_name";
3939
40- private final TableMetadata table;
40+ private final TableOrView parent;
4141 private final String name;
4242 private final DataType type;
4343 private final boolean isStatic;
@@ -46,14 +46,14 @@
4646 // between columns and indexes, and is updated only after the column is created
4747 final Map<String, IndexMetadata> indexes = new LinkedHashMap<String, IndexMetadata>();
4848
49- private ColumnMetadata(TableMetadata table, String name, DataType type, boolean isStatic) {
50- this.table = table;
49+ private ColumnMetadata(TableOrView parent, String name, DataType type, boolean isStatic) {
50+ this.parent = parent;
5151 this.name = name;
5252 this.type = type;
5353 this.isStatic = isStatic;
5454 }
5555
56- static ColumnMetadata fromRaw(TableMetadata tm, Raw raw) {
56+ static ColumnMetadata fromRaw(TableOrView tm, Raw raw) {
5757 return new ColumnMetadata(tm, raw.name, raw.dataType, raw.kind == Raw.Kind.STATIC);
5858 }
5959
@@ -71,12 +71,13 @@
7171 }
7272
7373 /**
74- * Returns the metadata of the table this column is part of.
74+ * Returns the parent object of this column. This can be a {@link TableMetadata}
75+ * or a {@link MaterializedViewMetadata} object.
7576 *
76- * @return the {@code TableMetadata} for the table this column is part of.
77+ * @return the parent object of this column.
7778 */
78- public TableMetadata getTable() {
79- return table;
79+ public TableOrView getParent() {
80+ return parent;
8081 }
8182
8283 /**
modified driver-core/src/main/java/com/datastax/driver/core/IndexMetadata.java +1 −1
@@ -116,7 +116,7 @@
116116 } else {
117117 options = SimpleJSONParser.parseStringMap(indexOptionsCol);
118118 }
119- return new IndexMetadata(column.getTable(), indexName, columns, indexType, TargetType.COLUMN, options);
119+ return new IndexMetadata((TableMetadata)column.getParent(), indexName, columns, indexType, TargetType.COLUMN, options);
120120 }
121121
122122 /**
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +30 −0
@@ -42,6 +42,7 @@
4242 private final Map<String, String> replication;
4343
4444 private final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>();
45+ private final Map<String, MaterializedViewMetadata> views = new ConcurrentHashMap<String, MaterializedViewMetadata>();
4546 private final Map<String, UserType> userTypes = new ConcurrentHashMap<String, UserType>();
4647 final Map<String, FunctionMetadata> functions = new ConcurrentHashMap<String, FunctionMetadata>();
4748 private final Map<String, AggregateMetadata> aggregates = new ConcurrentHashMap<String, AggregateMetadata>();
@@ -123,6 +124,31 @@
123124 return Collections.<TableMetadata>unmodifiableCollection(tables.values());
124125 }
125126
127+ /**
128+ * Returns the metadata for a materialized view contained in this keyspace.
129+ *
130+ * @param name the name of materialized view to retrieve
131+ * @return the metadata for materialized view {@code name} if it exists in this keyspace,
132+ * {@code null} otherwise.
133+ */
134+ public MaterializedViewMetadata getMaterializedView(String name) {
135+ return views.get(Metadata.handleId(name));
136+ }
137+
138+ void removeMaterializedView(String materializedView) {
139+ views.remove(materializedView);
140+ }
141+
142+ /**
143+ * Returns the materialized views defined in this keyspace.
144+ *
145+ * @return a collection of the metadata for the materialized views defined in this
146+ * keyspace.
147+ */
148+ public Collection<MaterializedViewMetadata> getMaterializedViews() {
149+ return Collections.unmodifiableCollection(views.values());
150+ }
151+
126152 /**
127153 * Returns the definition for a user defined type (UDT) in this keyspace.
128154 *
@@ -291,6 +317,10 @@
291317 tables.put(tm.getName(), tm);
292318 }
293319
320+ void add(MaterializedViewMetadata view) {
321+ views.put(view.getName(), view);
322+ }
323+
294324 void add(FunctionMetadata function) {
295325 functions.put(function.getFullName(), function);
296326 }
added driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java +218 −0
@@ -0,0 +1,218 @@
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.Joiner;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+
25+import static com.google.common.collect.Iterables.transform;
26+
27+/**
28+ * An immutable representation of a materialized view.
29+ * Materialized views are available starting from Cassandra 3.0.
30+ */
31+public class MaterializedViewMetadata extends TableOrView {
32+
33+ private static final Logger logger = LoggerFactory.getLogger(MaterializedViewMetadata.class);
34+
35+ private final TableMetadata baseTable;
36+
37+ private final boolean includeAllColumns;
38+
39+ private MaterializedViewMetadata(
40+ KeyspaceMetadata keyspace,
41+ TableMetadata baseTable,
42+ String name,
43+ UUID id,
44+ List<ColumnMetadata> partitionKey,
45+ List<ColumnMetadata> clusteringColumns,
46+ Map<String, ColumnMetadata> columns,
47+ boolean includeAllColumns,
48+ Options options,
49+ List<Order> clusteringOrder,
50+ VersionNumber cassandraVersion) {
51+ super(keyspace, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
52+ this.baseTable = baseTable;
53+ this.includeAllColumns = includeAllColumns;
54+ }
55+
56+ static MaterializedViewMetadata build(KeyspaceMetadata keyspace, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion) {
57+
58+ String name = row.getString("view_name");
59+ String tableName = row.getString("base_table_name");
60+ TableMetadata baseTable = keyspace.getTable(tableName);
61+ if(baseTable == null) {
62+ logger.trace(String.format("Cannot find base table %s for materialized view %s.%s: "
63+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will return null",
64+ tableName, keyspace.getName(), name, keyspace.getName(), name));
65+ return null;
66+ }
67+
68+ UUID id = row.getUUID("id");
69+ boolean includeAllColumns = row.getBool("include_all_columns");
70+
71+ int partitionKeySize = findCollectionSize(rawCols.values(), ColumnMetadata.Raw.Kind.PARTITION_KEY);
72+ int clusteringSize = findCollectionSize(rawCols.values(), ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN);
73+ List<ColumnMetadata> partitionKey = nullInitializedList(partitionKeySize);
74+ List<ColumnMetadata> clusteringColumns = nullInitializedList(clusteringSize);
75+ List<TableMetadata.Order> clusteringOrder = nullInitializedList(clusteringSize);
76+
77+ // We use a linked hashmap because we will keep this in the order of a 'SELECT * FROM ...'.
78+ LinkedHashMap<String, ColumnMetadata> columns = new LinkedHashMap<String, ColumnMetadata>();
79+
80+ TableMetadata.Options options = null;
81+ try {
82+ options = new Options(row, false, cassandraVersion);
83+ } catch (RuntimeException e) {
84+ // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
85+ // that tends to change often in Cassandra, it's worth special casing this.
86+ logger.error(String.format("Error parsing schema options for view %s.%s: "
87+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\").getOptions() will return null",
88+ keyspace.getName(), name, keyspace.getName(), name), e);
89+ }
90+
91+ MaterializedViewMetadata view = new MaterializedViewMetadata(
92+ keyspace, baseTable, name, id, partitionKey, clusteringColumns, columns,
93+ includeAllColumns, options, clusteringOrder, cassandraVersion);
94+
95+ // We use this temporary set just so non PK columns are added in lexicographical order, which is the one of a
96+ // 'SELECT * FROM ...'
97+ Set<ColumnMetadata> otherColumns = new TreeSet<ColumnMetadata>(columnMetadataComparator);
98+ for (ColumnMetadata.Raw rawCol : rawCols.values()) {
99+ ColumnMetadata col = ColumnMetadata.fromRaw(view, rawCol);
100+ switch (rawCol.kind) {
101+ case PARTITION_KEY:
102+ partitionKey.set(rawCol.position, col);
103+ break;
104+ case CLUSTERING_COLUMN:
105+ clusteringColumns.set(rawCol.position, col);
106+ clusteringOrder.set(rawCol.position, rawCol.isReversed ? Order.DESC : Order.ASC);
107+ break;
108+ default:
109+ otherColumns.add(col);
110+ break;
111+ }
112+ }
113+ for (ColumnMetadata c : partitionKey)
114+ columns.put(c.getName(), c);
115+ for (ColumnMetadata c : clusteringColumns)
116+ columns.put(c.getName(), c);
117+ for (ColumnMetadata c : otherColumns)
118+ columns.put(c.getName(), c);
119+
120+ baseTable.add(view);
121+
122+ return view;
123+
124+ }
125+
126+ private static int findCollectionSize(Collection<ColumnMetadata.Raw> cols, ColumnMetadata.Raw.Kind kind) {
127+ int maxId = -1;
128+ for (ColumnMetadata.Raw col : cols)
129+ if (col.kind == kind)
130+ maxId = Math.max(maxId, col.position);
131+ return maxId + 1;
132+ }
133+
134+ /**
135+ * Return this materialized view's base table.
136+ * @return this materialized view's base table.
137+ */
138+ public TableMetadata getBaseTable() {
139+ return baseTable;
140+ }
141+
142+ @Override
143+ protected String asCQLQuery(boolean formatted) {
144+
145+ String keyspaceName = Metadata.escapeId(keyspace.getName());
146+ String baseTableName = Metadata.escapeId(baseTable.getName());
147+ String viewName = Metadata.escapeId(name);
148+ String whereClause = Joiner.on(" AND ").join(transform(getPartitionKey(), new Function<ColumnMetadata, String>() {
149+ @Override
150+ public String apply(ColumnMetadata input) {
151+ return Metadata.escapeId(input.getName()) + " IS NOT NULL";
152+ }
153+ }));
154+
155+
156+ StringBuilder sb = new StringBuilder();
157+ sb.append("CREATE MATERIALIZED VIEW ")
158+ .append(keyspaceName).append('.').append(viewName)
159+ .append(" AS ");
160+ newLine(sb, formatted);
161+
162+ // SELECT
163+ sb.append("SELECT ");
164+ if(includeAllColumns) {
165+ sb.append(" * ");
166+ } else {
167+ Iterator<ColumnMetadata> it = columns.values().iterator();
168+ while(it.hasNext()) {
169+ ColumnMetadata column = it.next();
170+ sb.append(spaces(4, formatted)).append(Metadata.escapeId(column.getName()));
171+ if(it.hasNext()) sb.append(",");
172+ sb.append(" ");
173+ newLine(sb, formatted);
174+ }
175+ }
176+
177+ // FROM
178+ newLine(sb.append("FROM ").append(keyspaceName).append('.').append(baseTableName).append(" "), formatted);
179+
180+ // WHERE
181+ newLine(sb.append("WHERE "), formatted);
182+ Iterator<ColumnMetadata> it = getPrimaryKey().iterator();
183+ while(it.hasNext()) {
184+ ColumnMetadata column = it.next();
185+ sb.append(spaces(4, formatted)).append(Metadata.escapeId(column.getName()));
186+ sb.append(" IS NOT NULL");
187+ if(it.hasNext()) sb.append(" AND");
188+ sb.append(" ");
189+ newLine(sb, formatted);
190+ }
191+
192+ // PK
193+ sb.append("PRIMARY KEY (");
194+ if (partitionKey.size() == 1) {
195+ sb.append(partitionKey.get(0).getName());
196+ } else {
197+ sb.append('(');
198+ boolean first = true;
199+ for (ColumnMetadata cm : partitionKey) {
200+ if (first)
201+ first = false;
202+ else
203+ sb.append(", ");
204+ sb.append(Metadata.escapeId(cm.getName()));
205+ }
206+ sb.append(')');
207+ }
208+ for (ColumnMetadata cm : clusteringColumns)
209+ sb.append(", ").append(Metadata.escapeId(cm.getName()));
210+ sb.append(')');
211+ newLine(sb, formatted);
212+
213+ appendOptions(sb, formatted);
214+ return sb.toString();
215+
216+ }
217+
218+}
modified driver-core/src/main/java/com/datastax/driver/core/SchemaElement.java +6 −1
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+/**
19+ * Values for a SCHEMA_CHANGE event.
20+ * See protocol v4 section 4.2.6.
21+ * Note that {@code VIEW} is not a valid string under protocol v4 or lower, but is included for internal use only.
22+ */
1823 enum SchemaElement {
19- KEYSPACE, TABLE, TYPE, FUNCTION, AGGREGATE
24+ KEYSPACE, TABLE, TYPE, FUNCTION, AGGREGATE, VIEW
2025 }
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +55 −22
@@ -197,6 +197,7 @@
197197 private static final String SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions";
198198 private static final String SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates";
199199 private static final String SELECT_INDEXES = "SELECT * FROM system_schema.indexes";
200+ private static final String SELECT_VIEWS = "SELECT * FROM system_schema.views";
200201
201202 private static final String TABLE_NAME = "table_name";
202203
@@ -210,44 +211,33 @@
210211 ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
211212 CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
212213
213- String whereClause = "";
214- if (targetType != null) {
215- whereClause = " WHERE keyspace_name = '" + targetKeyspace + '\'';
216- if (targetType == TABLE)
217- whereClause += " AND table_name = '" + targetName + '\'';
218- else if (targetType == TYPE)
219- whereClause += " AND type_name = '" + targetName + '\'';
220- else if (targetType == FUNCTION)
221- whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
222- else if (targetType == AGGREGATE)
223- whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
224- }
225-
226214 ResultSetFuture ksFuture = null,
227215 udtFuture = null,
228216 cfFuture = null,
229217 colsFuture = null,
230218 functionsFuture = null,
231219 aggregatesFuture = null,
232- indexesFuture = null;
220+ indexesFuture = null,
221+ viewsFuture = null;
233222
234223 if (isSchemaOrKeyspace)
235- ksFuture = queryAsync(SELECT_KEYSPACES + whereClause, connection, protocolVersion);
224+ ksFuture = queryAsync(SELECT_KEYSPACES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
236225
237226 if (isSchemaOrKeyspace || targetType == TYPE)
238- udtFuture = queryAsync(SELECT_USERTYPES + whereClause, connection, protocolVersion);
227+ udtFuture = queryAsync(SELECT_USERTYPES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
239228
240229 if (isSchemaOrKeyspace || targetType == TABLE) {
241- cfFuture = queryAsync(SELECT_TABLES + whereClause, connection, protocolVersion);
242- colsFuture = queryAsync(SELECT_COLUMNS + whereClause, connection, protocolVersion);
243- indexesFuture = queryAsync(SELECT_INDEXES + whereClause, connection, protocolVersion);
230+ cfFuture = queryAsync(SELECT_TABLES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
231+ colsFuture = queryAsync(SELECT_COLUMNS + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
232+ indexesFuture = queryAsync(SELECT_INDEXES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
233+ viewsFuture = queryAsync(SELECT_VIEWS + whereClause(targetType == null ? null : VIEW, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
244234 }
245235
246- if ((isSchemaOrKeyspace || targetType == FUNCTION))
247- functionsFuture = queryAsync(SELECT_FUNCTIONS + whereClause, connection, protocolVersion);
236+ if (isSchemaOrKeyspace || targetType == FUNCTION)
237+ functionsFuture = queryAsync(SELECT_FUNCTIONS + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
248238
249239 if (isSchemaOrKeyspace || targetType == AGGREGATE)
250- aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause, connection, protocolVersion);
240+ aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
251241
252242 ResultSet ks = get(ksFuture);
253243 Map<String, List<Row>> udtDefs = groupByKeyspace(get(udtFuture));
@@ -255,6 +245,7 @@
255245 Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
256246 Map<String, List<Row>> functionDefs = groupByKeyspace(get(functionsFuture));
257247 Map<String, List<Row>> aggregateDefs = groupByKeyspace(get(aggregatesFuture));
248+ Map<String, List<Row>> viewDefs = groupByKeyspace(get(viewsFuture));
258249 Map<String, Map<String, List<Row>>> indexDefs = groupByKeyspaceAndCf(get(indexesFuture), TABLE_NAME);
259250
260251 metadata.lock.lock();
@@ -272,6 +263,9 @@
272263 if (cfDefs.containsKey(ksName)) {
273264 buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), indexDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
274265 }
266+ if (viewDefs.containsKey(ksName)) {
267+ buildViewMetadata(ksm, viewDefs.get(ksName), colsDefs.get(ksName), cassandraVersion);
268+ }
275269 if (functionDefs.containsKey(ksName)) {
276270 buildFunctionMetadata(ksm, functionDefs.get(ksName), protocolVersion, codecRegistry);
277271 }
@@ -307,6 +301,8 @@
307301 case TABLE:
308302 if (cfDefs.containsKey(targetKeyspace))
309303 buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), indexDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
304+ if (viewDefs.containsKey(targetKeyspace))
305+ buildViewMetadata(ksm, viewDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion);
310306 break;
311307 case TYPE:
312308 if (udtDefs.containsKey(targetKeyspace))
@@ -328,6 +324,25 @@
328324 metadata.lock.unlock();
329325 }
330326 }
327+
328+ private String whereClause(SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature) {
329+ String whereClause = "";
330+ if (targetType != null) {
331+ whereClause = " WHERE keyspace_name = '" + targetKeyspace + '\'';
332+ if (targetType == TABLE)
333+ whereClause += " AND table_name = '" + targetName + '\'';
334+ else if (targetType == VIEW)
335+ whereClause += " AND view_name = '" + targetName + '\'';
336+ else if (targetType == TYPE)
337+ whereClause += " AND type_name = '" + targetName + '\'';
338+ else if (targetType == FUNCTION)
339+ whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
340+ else if (targetType == AGGREGATE)
341+ whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
342+ }
343+ return whereClause;
344+ }
345+
331346 };
332347
333348 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) {
@@ -365,6 +380,24 @@
365380 }
366381 }
367382
383+ static void buildViewMetadata(KeyspaceMetadata ksm, List<Row> viewRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
384+ for (Row viewRow : viewRows) {
385+ String viewName = viewRow.getString("view_name");
386+ try {
387+ Map<String, ColumnMetadata.Raw> cols = colsDefs.get(viewName);
388+ if (cols == null || cols.isEmpty())
389+ continue; // we probably raced, we will update the metadata next time
390+ MaterializedViewMetadata view = MaterializedViewMetadata.build(ksm, viewRow, cols, cassandraVersion);
391+ if(view != null)
392+ ksm.add(view);
393+ } catch (RuntimeException e) {
394+ // See ControlConnection#refreshSchema for why we'd rather not probably this further
395+ logger.error(String.format("Error parsing schema for view %s.%s: "
396+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will be missing or incomplete",
397+ ksm.getName(), viewName, ksm.getName(), viewName), e);
398+ }
399+ }
400+ }
368401 static void buildUserTypes(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
369402 for (Row row : rows)
370403 ksm.add(UserType.build(row, protocolVersion, codecRegistry));
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +35 −579
@@ -17,16 +17,13 @@
1717
1818 import java.util.*;
1919
20-import com.google.common.base.Predicate;
21-import com.google.common.collect.ImmutableMap;
22-import com.google.common.collect.Iterables;
2320 import org.slf4j.Logger;
2421 import org.slf4j.LoggerFactory;
2522
2623 /**
2724 * Describes a Table.
2825 */
29-public class TableMetadata {
26+public class TableMetadata extends TableOrView {
3027
3128 private static final Logger logger = LoggerFactory.getLogger(TableMetadata.class);
3229
@@ -52,40 +49,8 @@
5249
5350 private static final String EMPTY_TYPE = "org.apache.cassandra.db.marshal.EmptyType";
5451
55- private static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
56- public int compare(ColumnMetadata c1, ColumnMetadata c2) {
57- return c1.getName().compareTo(c2.getName());
58- }
59- };
60-
61- private final KeyspaceMetadata keyspace;
62- private final String name;
63- private final UUID id;
64- private final List<ColumnMetadata> partitionKey;
65- private final List<ColumnMetadata> clusteringColumns;
66- private final Map<String, ColumnMetadata> columns;
6752 private final Map<String, IndexMetadata> indexes;
68- private final Options options;
69- private final List<Order> clusteringOrder;
70-
71-
72- private final VersionNumber cassandraVersion;
73-
74- /**
75- * Clustering orders.
76- * <p>
77- * This is used by {@link #getClusteringOrder} to indicate the clustering
78- * order of a table.
79- */
80- public static enum Order {
81- ASC, DESC;
82-
83- static final Predicate<Order> isAscending = new Predicate<Order>() {
84- public boolean apply(Order o) {
85- return o == ASC;
86- }
87- };
88- }
53+ private final Map<String, MaterializedViewMetadata> views;
8954
9055 private TableMetadata(KeyspaceMetadata keyspace,
9156 String name,
@@ -97,16 +62,9 @@
9762 Options options,
9863 List<Order> clusteringOrder,
9964 VersionNumber cassandraVersion) {
100- this.keyspace = keyspace;
101- this.name = name;
102- this.id = id;
103- this.partitionKey = partitionKey;
104- this.clusteringColumns = clusteringColumns;
105- this.columns = columns;
65+ super(keyspace, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
10666 this.indexes = indexes;
107- this.options = options;
108- this.clusteringOrder = clusteringOrder;
109- this.cassandraVersion = cassandraVersion;
67+ this.views = new HashMap<String, MaterializedViewMetadata>();
11068 }
11169
11270 static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, List<Row> indexRows, String nameColumn, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
@@ -270,6 +228,7 @@
270228 column.indexes.put(index.getName(), index);
271229 }
272230 }
231+
273232 return tm;
274233 }
275234
@@ -374,109 +333,6 @@
374333 }
375334 }
376335
377- private static <T> List<T> nullInitializedList(int size) {
378- List<T> l = new ArrayList<T>(size);
379- for (int i = 0; i < size; ++i)
380- l.add(null);
381- return l;
382- }
383-
384- /**
385- * Returns the name of this table.
386- *
387- * @return the name of this CQL table.
388- */
389- public String getName() {
390- return name;
391- }
392-
393- /**
394- * Returns the unique id of this table.
395- * <p>
396- * Note: this id is available in Cassandra 2.1 and above. It will be
397- * {@code null} for earlier versions.
398- *
399- * @return the unique id of the table.
400- */
401- public UUID getId() {
402- return id;
403- }
404-
405- /**
406- * Returns the keyspace this table belong to.
407- *
408- * @return the keyspace metadata of the keyspace this table belong to.
409- */
410- public KeyspaceMetadata getKeyspace() {
411- return keyspace;
412- }
413-
414- /**
415- * Returns metadata on a column of this table.
416- *
417- * @param name the name of the column to retrieve ({@code name} will be
418- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
419- * see {@link Metadata#quote}).
420- * @return the metadata for the column if it exists, or
421- * {@code null} otherwise.
422- */
423- public ColumnMetadata getColumn(String name) {
424- return columns.get(Metadata.handleId(name));
425- }
426-
427- /**
428- * Returns a list containing all the columns of this table.
429- *
430- * The order of the columns in the list is consistent with
431- * the order of the columns returned by a {@code SELECT * FROM thisTable}:
432- * the first column is the partition key, next are the clustering
433- * columns in their defined order, and then the rest of the
434- * columns follow in alphabetic order.
435- *
436- * @return a list containing the metadata for the columns of this table.
437- */
438- public List<ColumnMetadata> getColumns() {
439- return new ArrayList<ColumnMetadata>(columns.values());
440- }
441-
442- /**
443- * Returns the list of columns composing the primary key for this table.
444- *
445- * A table will always at least have a partition key (that
446- * may itself be one or more columns), so the returned list at least
447- * has one element.
448- *
449- * @return the list of columns composing the primary key for this table.
450- */
451- public List<ColumnMetadata> getPrimaryKey() {
452- List<ColumnMetadata> pk = new ArrayList<ColumnMetadata>(partitionKey.size() + clusteringColumns.size());
453- pk.addAll(partitionKey);
454- pk.addAll(clusteringColumns);
455- return pk;
456- }
457-
458- /**
459- * Returns the list of columns composing the partition key for this table.
460- *
461- * A table always has a partition key so the returned list has
462- * at least one element.
463- *
464- * @return the list of columns composing the partition key for this table.
465- */
466- public List<ColumnMetadata> getPartitionKey() {
467- return Collections.unmodifiableList(partitionKey);
468- }
469-
470- /**
471- * Returns the list of clustering columns for this table.
472- *
473- * @return the list of clustering columns for this table.
474- * If there is no clustering columns, an empty list is returned.
475- */
476- public List<ColumnMetadata> getClusteringColumns() {
477- return Collections.unmodifiableList(clusteringColumns);
478- }
479-
480336 /**
481337 * Returns metadata on a index of this table.
482338 *
@@ -500,32 +356,29 @@
500356 }
501357
502358 /**
503- * Returns the clustering order for this table.
504- * <p>
505- * The returned contains the clustering order of each clustering column. The
506- * {@code i}th element of the result correspond to the order (ascending or
507- * descending) of the {@code i}th clustering column (see
508- * {@link #getClusteringColumns}). Note that a table defined without any
509- * particular clustering order is equivalent to one for which all the
510- * clustering key are in ascending order.
359+ * Returns metadata on a view of this table.
511360 *
512- * @return a list with the clustering order for each clustering column.
361+ * @param name the name of the view to retrieve ({@code name} will be
362+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
363+ * see {@link Metadata#quote}).
364+ * @return the metadata for the {@code name} view if it exists, or
365+ * {@code null} otherwise.
513366 */
514- public List<Order> getClusteringOrder() {
515- return clusteringOrder;
367+ public MaterializedViewMetadata getView(String name) {
368+ return views.get(Metadata.handleId(name));
516369 }
517370
518371 /**
519- * Returns the options for this table.
372+ * Returns a list containing all the viewes of this table.
520373 *
521- * @return the options for this table.
374+ * @return a list containing the metadata for the viewes of this table.
522375 */
523- public Options getOptions() {
524- return options;
376+ public List<MaterializedViewMetadata> getViews() {
377+ return new ArrayList<MaterializedViewMetadata>(views.values());
525378 }
526379
527- void add(ColumnMetadata column) {
528- columns.put(column.getName(), column);
380+ void add(MaterializedViewMetadata view) {
381+ views.put(view.getName(), view);
529382 }
530383
531384 /**
@@ -533,8 +386,8 @@
533386 * table and the index on it.
534387 * <p>
535388 * In other words, this method returns the queries that would allow you to
536- * recreate the schema of this table, along with the indexes defined on
537- * columns of this table.
389+ * recreate the schema of this table, along with the indexes and views defined on
390+ * this table, if any.
538391 * <p>
539392 * Note that the returned String is formatted to be human readable (for
540393 * some definition of human readable at least).
@@ -542,36 +395,25 @@
542395 * @return the CQL queries representing this table schema as a {code
543396 * String}.
544397 */
398+ @Override
545399 public String exportAsString() {
546400 StringBuilder sb = new StringBuilder();
547401
548- sb.append(asCQLQuery(true));
402+ sb.append(super.exportAsString());
549403
550404 for (IndexMetadata index : indexes.values()) {
551405 sb.append('\n').append(index.asCQLQuery());
552406 }
553- return sb.toString();
554- }
555407
556- /**
557- * Returns a CQL query representing this table.
558- * <p>
559- * This method returns a single 'CREATE TABLE' query with the options
560- * corresponding to this table definition.
561- * <p>
562- * Note that the returned string is a single line; the returned query
563- * is not formatted in any way.
564- *
565- * @return the 'CREATE TABLE' query corresponding to this table.
566- * @see #exportAsString
567- */
568- public String asCQLQuery() {
569- return asCQLQuery(false);
408+ for (MaterializedViewMetadata index : views.values()) {
409+ sb.append('\n').append(index.asCQLQuery());
410+ }
411+
412+ return sb.toString();
570413 }
571414
572- private String asCQLQuery(boolean formatted) {
415+ protected String asCQLQuery(boolean formatted) {
573416 StringBuilder sb = new StringBuilder();
574-
575417 sb.append("CREATE TABLE ").append(Metadata.escapeId(keyspace.getName())).append('.').append(Metadata.escapeId(name)).append(" (");
576418 newLine(sb, formatted);
577419 for (ColumnMetadata cm : columns.values())
@@ -585,7 +427,10 @@
585427 sb.append('(');
586428 boolean first = true;
587429 for (ColumnMetadata cm : partitionKey) {
588- if (first) first = false; else sb.append(", ");
430+ if (first)
431+ first = false;
432+ else
433+ sb.append(", ");
589434 sb.append(Metadata.escapeId(cm.getName()));
590435 }
591436 sb.append(')');
@@ -596,397 +441,8 @@
596441 newLine(sb, formatted);
597442 // end PK
598443
599- // Options
600- sb.append(") WITH ");
601-
602- if (options.isCompactStorage)
603- and(sb.append("COMPACT STORAGE"), formatted);
604- if (!Iterables.all(clusteringOrder, Order.isAscending))
605- and(appendClusteringOrder(sb), formatted);
606- sb.append("read_repair_chance = ").append(options.readRepair);
607- and(sb, formatted).append("dclocal_read_repair_chance = ").append(options.localReadRepair);
608- if (cassandraVersion.getMajor() < 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0))
609- and(sb, formatted).append("replicate_on_write = ").append(options.replicateOnWrite);
610- and(sb, formatted).append("gc_grace_seconds = ").append(options.gcGrace);
611- and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.bfFpChance);
612- if (cassandraVersion.getMajor() < 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() < 1)
613- and(sb, formatted).append("caching = '").append(options.caching.get("keys")).append('\'');
614- else
615- and(sb, formatted).append("caching = ").append(formatOptionMap(options.caching));
616- if (options.comment != null)
617- and(sb, formatted).append("comment = '").append(options.comment.replace("'","''")).append('\'');
618- and(sb, formatted).append("compaction = ").append(formatOptionMap(options.compaction));
619- and(sb, formatted).append("compression = ").append(formatOptionMap(options.compression));
620- if (cassandraVersion.getMajor() >= 2) {
621- and(sb, formatted).append("default_time_to_live = ").append(options.defaultTTL);
622- and(sb, formatted).append("speculative_retry = '").append(options.speculativeRetry).append('\'');
623- if (options.indexInterval != null)
624- and(sb, formatted).append("index_interval = ").append(options.indexInterval);
625- }
626- if (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) {
627- and(sb, formatted).append("min_index_interval = ").append(options.minIndexInterval);
628- and(sb, formatted).append("max_index_interval = ").append(options.maxIndexInterval);
629- }
630- sb.append(';');
631- return sb.toString();
632- }
633-
634- @Override
635- public String toString() {
636- return asCQLQuery();
637- }
638-
639- private StringBuilder appendClusteringOrder(StringBuilder sb) {
640- sb.append("CLUSTERING ORDER BY (");
641- for (int i = 0; i < clusteringColumns.size(); i++) {
642- if (i > 0) sb.append(", ");
643- sb.append(clusteringColumns.get(i).getName()).append(' ').append(clusteringOrder.get(i));
644- }
645- return sb.append(')');
646- }
647-
648- private static String formatOptionMap(Map<String, String> m) {
649- StringBuilder sb = new StringBuilder();
650- sb.append("{ ");
651- boolean first = true;
652- for (Map.Entry<String, String> entry : m.entrySet()) {
653- if (first) first = false; else sb.append(", ");
654- sb.append('\'').append(entry.getKey()).append('\'');
655- sb.append(" : ");
656- try {
657- sb.append(Integer.parseInt(entry.getValue()));
658- } catch (NumberFormatException e) {
659- sb.append('\'').append(entry.getValue()).append('\'');
660- }
661- }
662- sb.append(" }");
663- return sb.toString();
664- }
665-
666- private StringBuilder and(StringBuilder sb, boolean formatted) {
667- return newLine(sb, formatted).append(spaces(2, formatted)).append(" AND ");
668- }
669-
670- static String spaces(int n, boolean formatted) {
671- if (!formatted)
672- return "";
673-
674- StringBuilder sb = new StringBuilder();
675- for (int i = 0; i < n; i++)
676- sb.append(' ');
677-
444+ sb.append(")");
445+ appendOptions(sb, formatted);
678446 return sb.toString();
679447 }
680-
681- static StringBuilder newLine(StringBuilder sb, boolean formatted) {
682- if (formatted)
683- sb.append('\n');
684- return sb;
685- }
686-
687- static StringBuilder spaceOrNewLine(StringBuilder sb, boolean formatted) {
688- sb.append(formatted ? '\n' : ' ');
689- return sb;
690- }
691-
692- public static class Options {
693-
694- private static final String COMMENT = "comment";
695- private static final String READ_REPAIR = "read_repair_chance";
696- private static final String DCLOCAL_READ_REPAIR = "dclocal_read_repair_chance";
697- private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
698- private static final String REPLICATE_ON_WRITE = "replicate_on_write";
699- private static final String GC_GRACE = "gc_grace_seconds";
700- private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
701- private static final String CACHING = "caching";
702- private static final String COMPACTION = "compaction";
703- private static final String COMPACTION_CLASS = "compaction_strategy_class";
704- private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
705- private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
706- private static final String COMPRESSION = "compression";
707- private static final String COMPRESSION_PARAMS = "compression_parameters";
708- private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
709- private static final String DEFAULT_TTL = "default_time_to_live";
710- private static final String SPECULATIVE_RETRY = "speculative_retry";
711- private static final String INDEX_INTERVAL = "index_interval";
712- private static final String MIN_INDEX_INTERVAL = "min_index_interval";
713- private static final String MAX_INDEX_INTERVAL = "max_index_interval";
714-
715- private static final boolean DEFAULT_REPLICATE_ON_WRITE = true;
716- private static final double DEFAULT_BF_FP_CHANCE = 0.01;
717- private static final boolean DEFAULT_POPULATE_CACHE_ON_FLUSH = false;
718- private static final int DEFAULT_MEMTABLE_FLUSH_PERIOD = 0;
719- private static final int DEFAULT_DEFAULT_TTL = 0;
720- private static final String DEFAULT_SPECULATIVE_RETRY = "NONE";
721- private static final int DEFAULT_INDEX_INTERVAL = 128;
722- private static final int DEFAULT_MIN_INDEX_INTERVAL = 128;
723- private static final int DEFAULT_MAX_INDEX_INTERVAL = 2048;
724-
725- private final boolean isCompactStorage;
726-
727- private final String comment;
728- private final double readRepair;
729- private final double localReadRepair;
730- private final boolean replicateOnWrite;
731- private final int gcGrace;
732- private final double bfFpChance;
733- private final Map<String, String> caching;
734- private final boolean populateCacheOnFlush;
735- private final int memtableFlushPeriodMs;
736- private final int defaultTTL;
737- private final String speculativeRetry;
738- private final Integer indexInterval;
739- private final Integer minIndexInterval;
740- private final Integer maxIndexInterval;
741- private final Map<String, String> compaction;
742- private final Map<String, String> compression;
743-
744- Options(Row row, boolean isCompactStorage, VersionNumber version) {
745-
746- boolean is120 = version.getMajor() < 2;
747- boolean is200 = version.getMajor() == 2 && version.getMinor() == 0;
748- boolean is210 = version.getMajor() == 2 && version.getMinor() >= 1;
749- boolean is300OrHigher = version.getMajor() > 2;
750- boolean is210OrHigher = is210 || is300OrHigher;
751-
752- this.isCompactStorage = isCompactStorage;
753- this.comment = isNullOrAbsent(row, COMMENT) ? "" : row.getString(COMMENT);
754- this.readRepair = row.getDouble(READ_REPAIR);
755-
756- if(is300OrHigher)
757- this.localReadRepair = row.getDouble(DCLOCAL_READ_REPAIR);
758- else
759- this.localReadRepair = row.getDouble(LOCAL_READ_REPAIR);
760-
761- this.replicateOnWrite = is210OrHigher || isNullOrAbsent(row, REPLICATE_ON_WRITE) ? DEFAULT_REPLICATE_ON_WRITE : row.getBool(REPLICATE_ON_WRITE);
762- this.gcGrace = row.getInt(GC_GRACE);
763- this.bfFpChance = isNullOrAbsent(row, BF_FP_CHANCE) ? DEFAULT_BF_FP_CHANCE : row.getDouble(BF_FP_CHANCE);
764-
765- this.populateCacheOnFlush = isNullOrAbsent(row, POPULATE_CACHE_ON_FLUSH) ? DEFAULT_POPULATE_CACHE_ON_FLUSH : row.getBool(POPULATE_CACHE_ON_FLUSH);
766- this.memtableFlushPeriodMs = is120 || isNullOrAbsent(row, MEMTABLE_FLUSH_PERIOD_MS) ? DEFAULT_MEMTABLE_FLUSH_PERIOD : row.getInt(MEMTABLE_FLUSH_PERIOD_MS);
767- this.defaultTTL = is120 || isNullOrAbsent(row, DEFAULT_TTL) ? DEFAULT_DEFAULT_TTL : row.getInt(DEFAULT_TTL);
768- this.speculativeRetry = is120 || isNullOrAbsent(row, SPECULATIVE_RETRY) ? DEFAULT_SPECULATIVE_RETRY : row.getString(SPECULATIVE_RETRY);
769-
770- if (is200)
771- this.indexInterval = isNullOrAbsent(row, INDEX_INTERVAL) ? DEFAULT_INDEX_INTERVAL : row.getInt(INDEX_INTERVAL);
772- else
773- this.indexInterval = null;
774-
775- if (is210OrHigher) {
776- this.minIndexInterval = isNullOrAbsent(row, MIN_INDEX_INTERVAL)
777- ? DEFAULT_MIN_INDEX_INTERVAL
778- : row.getInt(MIN_INDEX_INTERVAL);
779- this.maxIndexInterval = isNullOrAbsent(row, MAX_INDEX_INTERVAL)
780- ? DEFAULT_MAX_INDEX_INTERVAL
781- : row.getInt(MAX_INDEX_INTERVAL);
782- } else {
783- this.minIndexInterval = null;
784- this.maxIndexInterval = null;
785- }
786-
787- if (is300OrHigher) {
788- this.caching = ImmutableMap.copyOf(row.getMap(CACHING, String.class, String.class));
789- } else if (is210) {
790- this.caching = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(CACHING)));
791- } else {
792- this.caching = ImmutableMap.of("keys", row.getString(CACHING));
793- }
794-
795- if (is300OrHigher)
796- this.compaction = ImmutableMap.copyOf(row.getMap(COMPACTION, String.class, String.class));
797- else {
798- this.compaction = ImmutableMap.<String, String>builder()
799- .put("class", row.getString(COMPACTION_CLASS))
800- .putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)))
801- .build();
802- }
803-
804- if(is300OrHigher)
805- this.compression = ImmutableMap.copyOf(row.getMap(COMPRESSION, String.class, String.class));
806- else
807- this.compression = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(COMPRESSION_PARAMS)));
808- }
809-
810- private static boolean isNullOrAbsent(Row row, String name) {
811- return row.getColumnDefinitions().getIndexOf(name) < 0
812- || row.isNull(name);
813- }
814-
815- /**
816- * Returns whether the table uses the {@code COMPACT STORAGE} option.
817- *
818- * @return whether the table uses the {@code COMPACT STORAGE} option.
819- */
820- public boolean isCompactStorage() {
821- return isCompactStorage;
822- }
823-
824- /**
825- * Returns the commentary set for this table.
826- *
827- * @return the commentary set for this table, or {@code null} if noe has been set.
828- */
829- public String getComment() {
830- return comment;
831- }
832-
833- /**
834- * Returns the chance with which a read repair is triggered for this table.
835- *
836- * @return the read repair chance set for table (in [0.0, 1.0]).
837- */
838- public double getReadRepairChance() {
839- return readRepair;
840- }
841-
842- /**
843- * Returns the cluster local read repair chance set for this table.
844- *
845- * @return the local read repair chance set for table (in [0.0, 1.0]).
846- */
847- public double getLocalReadRepairChance() {
848- return localReadRepair;
849- }
850-
851- /**
852- * Returns whether replicateOnWrite is set for this table.
853- *
854- * This is only meaningful for tables holding counters.
855- *
856- * @return whether replicateOnWrite is set for this table.
857- */
858- public boolean getReplicateOnWrite() {
859- return replicateOnWrite;
860- }
861-
862- /**
863- * Returns the tombstone garbage collection grace time in seconds for this table.
864- *
865- * @return the tombstone garbage collection grace time in seconds for this table.
866- */
867- public int getGcGraceInSeconds() {
868- return gcGrace;
869- }
870-
871- /**
872- * Returns the false positive chance for the Bloom filter of this table.
873- *
874- * @return the Bloom filter false positive chance for this table (in [0.0, 1.0]).
875- */
876- public double getBloomFilterFalsePositiveChance() {
877- return bfFpChance;
878- }
879-
880- /**
881- * Returns the caching options for this table.
882- *
883- * @return an immutable map containing the caching options for this table.
884- */
885- public Map<String, String> getCaching() {
886- return caching;
887- }
888-
889- /**
890- * Whether the populate I/O cache on flush is set on this table.
891- *
892- * @return whether the populate I/O cache on flush is set on this table.
893- */
894- public boolean getPopulateIOCacheOnFlush() {
895- return populateCacheOnFlush;
896- }
897-
898- /*
899- * Returns the memtable flush period (in milliseconds) option for this table.
900- * <p>
901- * Note: this option is not available in Cassandra 1.2 and will return 0 (no periodic
902- * flush) when connected to 1.2 nodes.
903- *
904- * @return the memtable flush period option for this table or 0 if no
905- * periodic flush is configured.
906- */
907- public int getMemtableFlushPeriodInMs() {
908- return memtableFlushPeriodMs;
909- }
910-
911- /**
912- * Returns the default TTL for this table.
913- * <p>
914- * Note: this option is not available in Cassandra 1.2 and will return 0 (no default
915- * TTL) when connected to 1.2 nodes.
916- *
917- * @return the default TTL for this table or 0 if no default TTL is
918- * configured.
919- */
920- public int getDefaultTimeToLive() {
921- return defaultTTL;
922- }
923-
924- /**
925- * Returns the speculative retry option for this table.
926- * <p>
927- * Note: this option is not available in Cassandra 1.2 and will return "NONE" (no
928- * speculative retry) when connected to 1.2 nodes.
929- *
930- * @return the speculative retry option this table.
931- */
932- public String getSpeculativeRetry() {
933- return speculativeRetry;
934- }
935-
936- /**
937- * Returns the index interval option for this table.
938- * <p>
939- * Note: this option is not available in Cassandra 1.2 (more precisely, it is not
940- * configurable per-table) and will return 128 (the default index interval) when
941- * connected to 1.2 nodes. It is deprecated in Cassandra 2.1 and above, and will
942- * therefore return {@code null} for 2.1 nodes.
943- *
944- * @return the index interval option for this table.
945- */
946- public Integer getIndexInterval() {
947- return indexInterval;
948- }
949-
950- /**
951- * Returns the minimum index interval option for this table.
952- * <p>
953- * Note: this option is available in Cassandra 2.1 and above, and will return
954- * {@code null} for earlier versions.
955- *
956- * @return the minimum index interval option for this table.
957- */
958- public Integer getMinIndexInterval() {
959- return minIndexInterval;
960- }
961-
962- /**
963- * Returns the maximum index interval option for this table.
964- * <p>
965- * Note: this option is available in Cassandra 2.1 and above, and will return
966- * {@code null} for earlier versions.
967- *
968- * @return the maximum index interval option for this table.
969- */
970- public Integer getMaxIndexInterval() {
971- return maxIndexInterval;
972- }
973-
974- /**
975- * Returns the compaction options for this table.
976- *
977- * @return an immutable map containing the compaction options for this table.
978- */
979- public Map<String, String> getCompaction() {
980- return compaction;
981- }
982-
983- /**
984- * Returns the compression options for this table.
985- *
986- * @return an immutable map containing the compression options for this table.
987- */
988- public Map<String, String> getCompression() {
989- return compression;
990- }
991- }
992448 }
added driver-core/src/main/java/com/datastax/driver/core/TableOrView.java +642 −0
@@ -0,0 +1,642 @@
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.Predicate;
21+import com.google.common.collect.ImmutableMap;
22+import com.google.common.collect.Iterables;
23+
24+/**
25+ * Base class for Tables and Materialized Views.
26+ */
27+abstract class TableOrView {
28+
29+ static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
30+ public int compare(ColumnMetadata c1, ColumnMetadata c2) {
31+ return c1.getName().compareTo(c2.getName());
32+ }
33+ };
34+
35+ protected final KeyspaceMetadata keyspace;
36+ protected final String name;
37+ protected final UUID id;
38+ protected final List<ColumnMetadata> partitionKey;
39+ protected final List<ColumnMetadata> clusteringColumns;
40+ protected final Map<String, ColumnMetadata> columns;
41+ protected final Options options;
42+ protected final List<Order> clusteringOrder;
43+ protected final VersionNumber cassandraVersion;
44+
45+ /**
46+ * Clustering orders.
47+ * <p>
48+ * This is used by {@link #getClusteringOrder} to indicate the clustering
49+ * order of a table.
50+ */
51+ public enum Order {
52+ ASC, DESC;
53+
54+ static final Predicate<Order> isAscending = new Predicate<Order>() {
55+ public boolean apply(Order o) {
56+ return o == ASC;
57+ }
58+ };
59+ }
60+
61+ TableOrView(KeyspaceMetadata keyspace,
62+ String name,
63+ UUID id,
64+ List<ColumnMetadata> partitionKey,
65+ List<ColumnMetadata> clusteringColumns,
66+ Map<String, ColumnMetadata> columns,
67+ Options options,
68+ List<Order> clusteringOrder,
69+ VersionNumber cassandraVersion) {
70+ this.keyspace = keyspace;
71+ this.name = name;
72+ this.id = id;
73+ this.partitionKey = partitionKey;
74+ this.clusteringColumns = clusteringColumns;
75+ this.columns = columns;
76+ this.options = options;
77+ this.clusteringOrder = clusteringOrder;
78+ this.cassandraVersion = cassandraVersion;
79+ }
80+
81+ protected static <T> List<T> nullInitializedList(int size) {
82+ List<T> l = new ArrayList<T>(size);
83+ for (int i = 0; i < size; ++i)
84+ l.add(null);
85+ return l;
86+ }
87+
88+ /**
89+ * Returns the name of this table.
90+ *
91+ * @return the name of this CQL table.
92+ */
93+ public String getName() {
94+ return name;
95+ }
96+
97+ /**
98+ * Returns the unique id of this table.
99+ * <p>
100+ * Note: this id is available in Cassandra 2.1 and above. It will be
101+ * {@code null} for earlier versions.
102+ *
103+ * @return the unique id of the table.
104+ */
105+ public UUID getId() {
106+ return id;
107+ }
108+
109+ /**
110+ * Returns the keyspace this table belong to.
111+ *
112+ * @return the keyspace metadata of the keyspace this table belong to.
113+ */
114+ public KeyspaceMetadata getKeyspace() {
115+ return keyspace;
116+ }
117+
118+ /**
119+ * Returns metadata on a column of this table.
120+ *
121+ * @param name the name of the column to retrieve ({@code name} will be
122+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
123+ * see {@link Metadata#quote}).
124+ * @return the metadata for the column if it exists, or
125+ * {@code null} otherwise.
126+ */
127+ public ColumnMetadata getColumn(String name) {
128+ return columns.get(Metadata.handleId(name));
129+ }
130+
131+ /**
132+ * Returns a list containing all the columns of this table.
133+ *
134+ * The order of the columns in the list is consistent with
135+ * the order of the columns returned by a {@code SELECT * FROM thisTable}:
136+ * the first column is the partition key, next are the clustering
137+ * columns in their defined order, and then the rest of the
138+ * columns follow in alphabetic order.
139+ *
140+ * @return a list containing the metadata for the columns of this table.
141+ */
142+ public List<ColumnMetadata> getColumns() {
143+ return new ArrayList<ColumnMetadata>(columns.values());
144+ }
145+
146+ /**
147+ * Returns the list of columns composing the primary key for this table.
148+ *
149+ * A table will always at least have a partition key (that
150+ * may itself be one or more columns), so the returned list at least
151+ * has one element.
152+ *
153+ * @return the list of columns composing the primary key for this table.
154+ */
155+ public List<ColumnMetadata> getPrimaryKey() {
156+ List<ColumnMetadata> pk = new ArrayList<ColumnMetadata>(partitionKey.size() + clusteringColumns.size());
157+ pk.addAll(partitionKey);
158+ pk.addAll(clusteringColumns);
159+ return pk;
160+ }
161+
162+ /**
163+ * Returns the list of columns composing the partition key for this table.
164+ *
165+ * A table always has a partition key so the returned list has
166+ * at least one element.
167+ *
168+ * @return the list of columns composing the partition key for this table.
169+ */
170+ public List<ColumnMetadata> getPartitionKey() {
171+ return Collections.unmodifiableList(partitionKey);
172+ }
173+
174+ /**
175+ * Returns the list of clustering columns for this table.
176+ *
177+ * @return the list of clustering columns for this table.
178+ * If there is no clustering columns, an empty list is returned.
179+ */
180+ public List<ColumnMetadata> getClusteringColumns() {
181+ return Collections.unmodifiableList(clusteringColumns);
182+ }
183+
184+ /**
185+ * Returns the clustering order for this table.
186+ * <p>
187+ * The returned contains the clustering order of each clustering column. The
188+ * {@code i}th element of the result correspond to the order (ascending or
189+ * descending) of the {@code i}th clustering column (see
190+ * {@link #getClusteringColumns}). Note that a table defined without any
191+ * particular clustering order is equivalent to one for which all the
192+ * clustering key are in ascending order.
193+ *
194+ * @return a list with the clustering order for each clustering column.
195+ */
196+ public List<Order> getClusteringOrder() {
197+ return clusteringOrder;
198+ }
199+
200+ /**
201+ * Returns the options for this table.
202+ *
203+ * @return the options for this table.
204+ */
205+ public Options getOptions() {
206+ return options;
207+ }
208+
209+ void add(ColumnMetadata column) {
210+ columns.put(column.getName(), column);
211+ }
212+
213+ /**
214+ * Returns a {@code String} containing CQL queries representing this
215+ * table and the index on it.
216+ * <p>
217+ * In other words, this method returns the queries that would allow you to
218+ * recreate the schema of this table, along with the indexes and views defined on
219+ * this table, if any.
220+ * <p>
221+ * Note that the returned String is formatted to be human readable (for
222+ * some definition of human readable at least).
223+ *
224+ * @return the CQL queries representing this table schema as a {code
225+ * String}.
226+ */
227+ public String exportAsString() {
228+ return asCQLQuery(true);
229+ }
230+
231+ /**
232+ * Returns a CQL query representing this table.
233+ * <p>
234+ * This method returns a single 'CREATE TABLE' query with the options
235+ * corresponding to this table definition.
236+ * <p>
237+ * Note that the returned string is a single line; the returned query
238+ * is not formatted in any way.
239+ *
240+ * @return the 'CREATE TABLE' query corresponding to this table.
241+ * @see #exportAsString
242+ */
243+ public String asCQLQuery() {
244+ return asCQLQuery(false);
245+ }
246+
247+ protected abstract String asCQLQuery(boolean formatted);
248+
249+ protected StringBuilder appendOptions(StringBuilder sb, boolean formatted){
250+ // Options
251+ sb.append(" WITH ");
252+ if (options.isCompactStorage)
253+ and(sb.append("COMPACT STORAGE"), formatted);
254+ if (!Iterables.all(clusteringOrder, Order.isAscending))
255+ and(appendClusteringOrder(sb), formatted);
256+ sb.append("read_repair_chance = ").append(options.readRepair);
257+ and(sb, formatted).append("dclocal_read_repair_chance = ").append(options.localReadRepair);
258+ if (cassandraVersion.getMajor() < 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0))
259+ and(sb, formatted).append("replicate_on_write = ").append(options.replicateOnWrite);
260+ and(sb, formatted).append("gc_grace_seconds = ").append(options.gcGrace);
261+ and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.bfFpChance);
262+ if (cassandraVersion.getMajor() < 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() < 1)
263+ and(sb, formatted).append("caching = '").append(options.caching.get("keys")).append('\'');
264+ else
265+ and(sb, formatted).append("caching = ").append(formatOptionMap(options.caching));
266+ if (options.comment != null)
267+ and(sb, formatted).append("comment = '").append(options.comment.replace("'","''")).append('\'');
268+ and(sb, formatted).append("compaction = ").append(formatOptionMap(options.compaction));
269+ and(sb, formatted).append("compression = ").append(formatOptionMap(options.compression));
270+ if (cassandraVersion.getMajor() >= 2) {
271+ and(sb, formatted).append("default_time_to_live = ").append(options.defaultTTL);
272+ and(sb, formatted).append("speculative_retry = '").append(options.speculativeRetry).append('\'');
273+ if (options.indexInterval != null)
274+ and(sb, formatted).append("index_interval = ").append(options.indexInterval);
275+ }
276+ if (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) {
277+ and(sb, formatted).append("min_index_interval = ").append(options.minIndexInterval);
278+ and(sb, formatted).append("max_index_interval = ").append(options.maxIndexInterval);
279+ }
280+ sb.append(';');
281+ return sb;
282+ }
283+
284+ @Override
285+ public String toString() {
286+ return asCQLQuery();
287+ }
288+
289+ private StringBuilder appendClusteringOrder(StringBuilder sb) {
290+ sb.append("CLUSTERING ORDER BY (");
291+ for (int i = 0; i < clusteringColumns.size(); i++) {
292+ if (i > 0) sb.append(", ");
293+ sb.append(clusteringColumns.get(i).getName()).append(' ').append(clusteringOrder.get(i));
294+ }
295+ return sb.append(')');
296+ }
297+
298+ private static String formatOptionMap(Map<String, String> m) {
299+ StringBuilder sb = new StringBuilder();
300+ sb.append("{ ");
301+ boolean first = true;
302+ for (Map.Entry<String, String> entry : m.entrySet()) {
303+ if (first) first = false; else sb.append(", ");
304+ sb.append('\'').append(entry.getKey()).append('\'');
305+ sb.append(" : ");
306+ try {
307+ sb.append(Integer.parseInt(entry.getValue()));
308+ } catch (NumberFormatException e) {
309+ sb.append('\'').append(entry.getValue()).append('\'');
310+ }
311+ }
312+ sb.append(" }");
313+ return sb.toString();
314+ }
315+
316+ private StringBuilder and(StringBuilder sb, boolean formatted) {
317+ return newLine(sb, formatted).append(spaces(2, formatted)).append(" AND ");
318+ }
319+
320+ static String spaces(int n, boolean formatted) {
321+ if (!formatted)
322+ return "";
323+
324+ StringBuilder sb = new StringBuilder();
325+ for (int i = 0; i < n; i++)
326+ sb.append(' ');
327+
328+ return sb.toString();
329+ }
330+
331+ static StringBuilder newLine(StringBuilder sb, boolean formatted) {
332+ if (formatted)
333+ sb.append('\n');
334+ return sb;
335+ }
336+
337+ static StringBuilder spaceOrNewLine(StringBuilder sb, boolean formatted) {
338+ sb.append(formatted ? '\n' : ' ');
339+ return sb;
340+ }
341+
342+ public static class Options {
343+
344+ private static final String COMMENT = "comment";
345+ private static final String READ_REPAIR = "read_repair_chance";
346+ private static final String DCLOCAL_READ_REPAIR = "dclocal_read_repair_chance";
347+ private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
348+ private static final String REPLICATE_ON_WRITE = "replicate_on_write";
349+ private static final String GC_GRACE = "gc_grace_seconds";
350+ private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
351+ private static final String CACHING = "caching";
352+ private static final String COMPACTION = "compaction";
353+ private static final String COMPACTION_CLASS = "compaction_strategy_class";
354+ private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
355+ private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
356+ private static final String COMPRESSION = "compression";
357+ private static final String COMPRESSION_PARAMS = "compression_parameters";
358+ private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
359+ private static final String DEFAULT_TTL = "default_time_to_live";
360+ private static final String SPECULATIVE_RETRY = "speculative_retry";
361+ private static final String INDEX_INTERVAL = "index_interval";
362+ private static final String MIN_INDEX_INTERVAL = "min_index_interval";
363+ private static final String MAX_INDEX_INTERVAL = "max_index_interval";
364+
365+ private static final boolean DEFAULT_REPLICATE_ON_WRITE = true;
366+ private static final double DEFAULT_BF_FP_CHANCE = 0.01;
367+ private static final boolean DEFAULT_POPULATE_CACHE_ON_FLUSH = false;
368+ private static final int DEFAULT_MEMTABLE_FLUSH_PERIOD = 0;
369+ private static final int DEFAULT_DEFAULT_TTL = 0;
370+ private static final String DEFAULT_SPECULATIVE_RETRY = "NONE";
371+ private static final int DEFAULT_INDEX_INTERVAL = 128;
372+ private static final int DEFAULT_MIN_INDEX_INTERVAL = 128;
373+ private static final int DEFAULT_MAX_INDEX_INTERVAL = 2048;
374+
375+ private final boolean isCompactStorage;
376+
377+ private final String comment;
378+ private final double readRepair;
379+ private final double localReadRepair;
380+ private final boolean replicateOnWrite;
381+ private final int gcGrace;
382+ private final double bfFpChance;
383+ private final Map<String, String> caching;
384+ private final boolean populateCacheOnFlush;
385+ private final int memtableFlushPeriodMs;
386+ private final int defaultTTL;
387+ private final String speculativeRetry;
388+ private final Integer indexInterval;
389+ private final Integer minIndexInterval;
390+ private final Integer maxIndexInterval;
391+ private final Map<String, String> compaction;
392+ private final Map<String, String> compression;
393+
394+ Options(Row row, boolean isCompactStorage, VersionNumber version) {
395+
396+ boolean is120 = version.getMajor() < 2;
397+ boolean is200 = version.getMajor() == 2 && version.getMinor() == 0;
398+ boolean is210 = version.getMajor() == 2 && version.getMinor() >= 1;
399+ boolean is300OrHigher = version.getMajor() > 2;
400+ boolean is210OrHigher = is210 || is300OrHigher;
401+
402+ this.isCompactStorage = isCompactStorage;
403+ this.comment = isNullOrAbsent(row, COMMENT) ? "" : row.getString(COMMENT);
404+ this.readRepair = row.getDouble(READ_REPAIR);
405+
406+ if(is300OrHigher)
407+ this.localReadRepair = row.getDouble(DCLOCAL_READ_REPAIR);
408+ else
409+ this.localReadRepair = row.getDouble(LOCAL_READ_REPAIR);
410+
411+ this.replicateOnWrite = is210OrHigher || isNullOrAbsent(row, REPLICATE_ON_WRITE) ? DEFAULT_REPLICATE_ON_WRITE : row.getBool(REPLICATE_ON_WRITE);
412+ this.gcGrace = row.getInt(GC_GRACE);
413+ this.bfFpChance = isNullOrAbsent(row, BF_FP_CHANCE) ? DEFAULT_BF_FP_CHANCE : row.getDouble(BF_FP_CHANCE);
414+
415+ this.populateCacheOnFlush = isNullOrAbsent(row, POPULATE_CACHE_ON_FLUSH) ? DEFAULT_POPULATE_CACHE_ON_FLUSH : row.getBool(POPULATE_CACHE_ON_FLUSH);
416+ this.memtableFlushPeriodMs = is120 || isNullOrAbsent(row, MEMTABLE_FLUSH_PERIOD_MS) ? DEFAULT_MEMTABLE_FLUSH_PERIOD : row.getInt(MEMTABLE_FLUSH_PERIOD_MS);
417+ this.defaultTTL = is120 || isNullOrAbsent(row, DEFAULT_TTL) ? DEFAULT_DEFAULT_TTL : row.getInt(DEFAULT_TTL);
418+ this.speculativeRetry = is120 || isNullOrAbsent(row, SPECULATIVE_RETRY) ? DEFAULT_SPECULATIVE_RETRY : row.getString(SPECULATIVE_RETRY);
419+
420+ if (is200)
421+ this.indexInterval = isNullOrAbsent(row, INDEX_INTERVAL) ? DEFAULT_INDEX_INTERVAL : row.getInt(INDEX_INTERVAL);
422+ else
423+ this.indexInterval = null;
424+
425+ if (is210OrHigher) {
426+ this.minIndexInterval = isNullOrAbsent(row, MIN_INDEX_INTERVAL)
427+ ? DEFAULT_MIN_INDEX_INTERVAL
428+ : row.getInt(MIN_INDEX_INTERVAL);
429+ this.maxIndexInterval = isNullOrAbsent(row, MAX_INDEX_INTERVAL)
430+ ? DEFAULT_MAX_INDEX_INTERVAL
431+ : row.getInt(MAX_INDEX_INTERVAL);
432+ } else {
433+ this.minIndexInterval = null;
434+ this.maxIndexInterval = null;
435+ }
436+
437+ if (is300OrHigher) {
438+ this.caching = ImmutableMap.copyOf(row.getMap(CACHING, String.class, String.class));
439+ } else if (is210) {
440+ this.caching = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(CACHING)));
441+ } else {
442+ this.caching = ImmutableMap.of("keys", row.getString(CACHING));
443+ }
444+
445+ if (is300OrHigher)
446+ this.compaction = ImmutableMap.copyOf(row.getMap(COMPACTION, String.class, String.class));
447+ else {
448+ this.compaction = ImmutableMap.<String, String>builder()
449+ .put("class", row.getString(COMPACTION_CLASS))
450+ .putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)))
451+ .build();
452+ }
453+
454+ if(is300OrHigher)
455+ this.compression = ImmutableMap.copyOf(row.getMap(COMPRESSION, String.class, String.class));
456+ else
457+ this.compression = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(COMPRESSION_PARAMS)));
458+ }
459+
460+ private static boolean isNullOrAbsent(Row row, String name) {
461+ return row.getColumnDefinitions().getIndexOf(name) < 0
462+ || row.isNull(name);
463+ }
464+
465+ /**
466+ * Returns whether the table uses the {@code COMPACT STORAGE} option.
467+ *
468+ * @return whether the table uses the {@code COMPACT STORAGE} option.
469+ */
470+ public boolean isCompactStorage() {
471+ return isCompactStorage;
472+ }
473+
474+ /**
475+ * Returns the commentary set for this table.
476+ *
477+ * @return the commentary set for this table, or {@code null} if noe has been set.
478+ */
479+ public String getComment() {
480+ return comment;
481+ }
482+
483+ /**
484+ * Returns the chance with which a read repair is triggered for this table.
485+ *
486+ * @return the read repair chance set for table (in [0.0, 1.0]).
487+ */
488+ public double getReadRepairChance() {
489+ return readRepair;
490+ }
491+
492+ /**
493+ * Returns the cluster local read repair chance set for this table.
494+ *
495+ * @return the local read repair chance set for table (in [0.0, 1.0]).
496+ */
497+ public double getLocalReadRepairChance() {
498+ return localReadRepair;
499+ }
500+
501+ /**
502+ * Returns whether replicateOnWrite is set for this table.
503+ *
504+ * This is only meaningful for tables holding counters.
505+ *
506+ * @return whether replicateOnWrite is set for this table.
507+ */
508+ public boolean getReplicateOnWrite() {
509+ return replicateOnWrite;
510+ }
511+
512+ /**
513+ * Returns the tombstone garbage collection grace time in seconds for this table.
514+ *
515+ * @return the tombstone garbage collection grace time in seconds for this table.
516+ */
517+ public int getGcGraceInSeconds() {
518+ return gcGrace;
519+ }
520+
521+ /**
522+ * Returns the false positive chance for the Bloom filter of this table.
523+ *
524+ * @return the Bloom filter false positive chance for this table (in [0.0, 1.0]).
525+ */
526+ public double getBloomFilterFalsePositiveChance() {
527+ return bfFpChance;
528+ }
529+
530+ /**
531+ * Returns the caching options for this table.
532+ *
533+ * @return an immutable map containing the caching options for this table.
534+ */
535+ public Map<String, String> getCaching() {
536+ return caching;
537+ }
538+
539+ /**
540+ * Whether the populate I/O cache on flush is set on this table.
541+ *
542+ * @return whether the populate I/O cache on flush is set on this table.
543+ */
544+ public boolean getPopulateIOCacheOnFlush() {
545+ return populateCacheOnFlush;
546+ }
547+
548+ /*
549+ * Returns the memtable flush period (in milliseconds) option for this table.
550+ * <p>
551+ * Note: this option is not available in Cassandra 1.2 and will return 0 (no periodic
552+ * flush) when connected to 1.2 nodes.
553+ *
554+ * @return the memtable flush period option for this table or 0 if no
555+ * periodic flush is configured.
556+ */
557+ public int getMemtableFlushPeriodInMs() {
558+ return memtableFlushPeriodMs;
559+ }
560+
561+ /**
562+ * Returns the default TTL for this table.
563+ * <p>
564+ * Note: this option is not available in Cassandra 1.2 and will return 0 (no default
565+ * TTL) when connected to 1.2 nodes.
566+ *
567+ * @return the default TTL for this table or 0 if no default TTL is
568+ * configured.
569+ */
570+ public int getDefaultTimeToLive() {
571+ return defaultTTL;
572+ }
573+
574+ /**
575+ * Returns the speculative retry option for this table.
576+ * <p>
577+ * Note: this option is not available in Cassandra 1.2 and will return "NONE" (no
578+ * speculative retry) when connected to 1.2 nodes.
579+ *
580+ * @return the speculative retry option this table.
581+ */
582+ public String getSpeculativeRetry() {
583+ return speculativeRetry;
584+ }
585+
586+ /**
587+ * Returns the index interval option for this table.
588+ * <p>
589+ * Note: this option is not available in Cassandra 1.2 (more precisely, it is not
590+ * configurable per-table) and will return 128 (the default index interval) when
591+ * connected to 1.2 nodes. It is deprecated in Cassandra 2.1 and above, and will
592+ * therefore return {@code null} for 2.1 nodes.
593+ *
594+ * @return the index interval option for this table.
595+ */
596+ public Integer getIndexInterval() {
597+ return indexInterval;
598+ }
599+
600+ /**
601+ * Returns the minimum index interval option for this table.
602+ * <p>
603+ * Note: this option is available in Cassandra 2.1 and above, and will return
604+ * {@code null} for earlier versions.
605+ *
606+ * @return the minimum index interval option for this table.
607+ */
608+ public Integer getMinIndexInterval() {
609+ return minIndexInterval;
610+ }
611+
612+ /**
613+ * Returns the maximum index interval option for this table.
614+ * <p>
615+ * Note: this option is available in Cassandra 2.1 and above, and will return
616+ * {@code null} for earlier versions.
617+ *
618+ * @return the maximum index interval option for this table.
619+ */
620+ public Integer getMaxIndexInterval() {
621+ return maxIndexInterval;
622+ }
623+
624+ /**
625+ * Returns the compaction options for this table.
626+ *
627+ * @return an immutable map containing the compaction options for this table.
628+ */
629+ public Map<String, String> getCompaction() {
630+ return compaction;
631+ }
632+
633+ /**
634+ * Returns the compression options for this table.
635+ *
636+ * @return an immutable map containing the compression options for this table.
637+ */
638+ public Map<String, String> getCompression() {
639+ return compression;
640+ }
641+ }
642+}
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
@@ -55,4 +55,8 @@
5555 return new TypeCodecAssert(codec);
5656 }
5757
58+ public static MaterializedViewMetadataAssert assertThat(MaterializedViewMetadata view) {
59+ return new MaterializedViewMetadataAssert(view);
60+ }
61+
5862 }
modified driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java +6 −6
@@ -36,27 +36,27 @@
3636 }
3737
3838 public ColumnMetadataAssert isPrimaryKey() {
39- assertThat(actual.getTable().getPrimaryKey().contains(actual));
39+ assertThat(actual.getParent().getPrimaryKey().contains(actual));
4040 return this;
4141 }
4242
4343 public ColumnMetadataAssert isPartitionKey() {
44- assertThat(actual.getTable().getPartitionKey().contains(actual));
44+ assertThat(actual.getParent().getPartitionKey().contains(actual));
4545 return this;
4646 }
4747
4848 public ColumnMetadataAssert isClusteringColumn() {
49- assertThat(actual.getTable().getClusteringColumns().contains(actual));
49+ assertThat(actual.getParent().getClusteringColumns().contains(actual));
5050 return this;
5151 }
5252
5353 public ColumnMetadataAssert isRegularColumn() {
54- assertThat(!actual.getTable().getPrimaryKey().contains(actual));
54+ assertThat(!actual.getParent().getPrimaryKey().contains(actual));
5555 return this;
5656 }
5757
58- public ColumnMetadataAssert hasClusteringOrder(TableMetadata.Order order) {
59- assertThat(actual.getTable().getClusteringOrder().get(actual.getTable().getClusteringColumns().indexOf(actual))).isEqualTo(order);
58+ public ColumnMetadataAssert hasClusteringOrder(TableOrView.Order order) {
59+ assertThat(actual.getParent().getClusteringOrder().get(actual.getParent().getClusteringColumns().indexOf(actual))).isEqualTo(order);
6060 return this;
6161 }
6262
added driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataAssert.java +43 −0
@@ -0,0 +1,43 @@
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 org.assertj.core.api.AbstractAssert;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+public class MaterializedViewMetadataAssert extends AbstractAssert<MaterializedViewMetadataAssert, MaterializedViewMetadata> {
23+
24+ public MaterializedViewMetadataAssert(MaterializedViewMetadata actual) {
25+ super(actual, MaterializedViewMetadataAssert.class);
26+ }
27+
28+ public MaterializedViewMetadataAssert hasName(String name) {
29+ assertThat(actual.getName()).isEqualTo(name);
30+ return this;
31+ }
32+
33+ public MaterializedViewMetadataAssert hasBaseTable(TableMetadata table) {
34+ assertThat(actual.getBaseTable()).isEqualTo(table);
35+ return this;
36+ }
37+
38+ public MaterializedViewMetadataAssert hasNumberOfColumns(int expected) {
39+ assertThat(actual.getColumns().size()).isEqualTo(expected);
40+ return this;
41+ }
42+
43+}
added driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java +120 −0
@@ -0,0 +1,120 @@
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.Collection;
19+import java.util.Collections;
20+
21+import org.testng.annotations.Test;
22+
23+import com.datastax.driver.core.utils.CassandraVersion;
24+
25+import static com.datastax.driver.core.Assertions.assertThat;
26+import static com.datastax.driver.core.DataType.*;
27+import static com.datastax.driver.core.TableOrView.Order.DESC;
28+
29+@CassandraVersion(major = 3)
30+public class MaterializedViewMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
31+
32+ @Test(groups = "short")
33+ public void should_create_view_metadata() {
34+
35+ // given
36+ String createTable = String.format(
37+ "CREATE TABLE %s.scores("
38+ + "user TEXT,"
39+ + "game TEXT,"
40+ + "year INT,"
41+ + "month INT,"
42+ + "day INT,"
43+ + "score INT,"
44+ + "PRIMARY KEY (user, game, year, month, day)"
45+ + ")",
46+ keyspace);
47+ String createMV = String.format(
48+ "CREATE MATERIALIZED VIEW %s.monthlyhigh AS "
49+ + "SELECT user FROM %s.scores "
50+ + "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 "
51+ + "PRIMARY KEY ((game, year, month), score, user, day) "
52+ + "WITH CLUSTERING ORDER BY (score DESC)",
53+ keyspace, keyspace);
54+
55+ // when
56+ session.execute(createTable);
57+ session.execute(createMV);
58+
59+ // then
60+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("scores");
61+ MaterializedViewMetadata mv = cluster.getMetadata().getKeyspace(keyspace).getMaterializedView("monthlyhigh");
62+
63+ assertThat(table).isNotNull().hasName("scores").hasMaterializedView(mv).hasNumberOfColumns(6);
64+ assertThat(table.getColumns().get(0)).isNotNull().hasName("user").isPartitionKey();
65+ assertThat(table.getColumns().get(1)).isNotNull().hasName("game").isClusteringColumn();
66+ assertThat(table.getColumns().get(2)).isNotNull().hasName("year").isClusteringColumn();
67+ assertThat(table.getColumns().get(3)).isNotNull().hasName("month").isClusteringColumn();
68+ assertThat(table.getColumns().get(4)).isNotNull().hasName("day").isClusteringColumn();
69+ assertThat(table.getColumns().get(5)).isNotNull().hasName("score").isRegularColumn();
70+
71+ assertThat(mv).isNotNull().hasName("monthlyhigh").hasBaseTable(table).hasNumberOfColumns(6).isEqualTo(table.getView("monthlyhigh"));
72+ assertThat(mv.getColumns().get(0)).isNotNull().hasName("game").isPartitionKey();
73+ assertThat(mv.getColumns().get(1)).isNotNull().hasName("year").isPartitionKey();
74+ assertThat(mv.getColumns().get(2)).isNotNull().hasName("month").isPartitionKey();
75+ assertThat(mv.getColumns().get(3)).isNotNull().hasName("score").isClusteringColumn().hasClusteringOrder(DESC);
76+ assertThat(mv.getColumns().get(4)).isNotNull().hasName("user").isClusteringColumn();
77+ assertThat(mv.getColumns().get(5)).isNotNull().hasName("day").isClusteringColumn();
78+
79+ assertThat(mv.asCQLQuery(false)).contains(createMV);
80+
81+ }
82+
83+ @Test(groups = "short")
84+ public void should_create_view_metadata_with_case_sensitive_column_names() {
85+ // given
86+ String createTable = String.format(
87+ "CREATE TABLE %s.t1 ("
88+ + "\"theKey\" int, "
89+ + "\"theClustering\" int, "
90+ + "\"theValue\" int, "
91+ + "PRIMARY KEY (\"theKey\", \"theClustering\"))",
92+ keyspace);
93+ String createMV = String.format(
94+ "CREATE MATERIALIZED VIEW %s.mv1 AS "
95+ + "SELECT \"theKey\", \"theClustering\", \"theValue\" "
96+ + "FROM %s.t1 "
97+ + "WHERE \"theKey\" IS NOT NULL AND \"theClustering\" IS NOT NULL AND \"theValue\" IS NOT NULL "
98+ + "PRIMARY KEY (\"theKey\", \"theClustering\")",
99+ keyspace, keyspace);
100+ // when
101+ session.execute(createTable);
102+ session.execute(createMV);
103+ // then
104+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("t1");
105+ MaterializedViewMetadata mv = cluster.getMetadata().getKeyspace(keyspace).getMaterializedView("mv1");
106+ assertThat(table).isNotNull().hasName("t1").hasMaterializedView(mv).hasNumberOfColumns(3);
107+ 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());
110+ assertThat(mv).isNotNull().hasName("mv1").hasBaseTable(table).hasNumberOfColumns(3);
111+ 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());
114+ }
115+
116+ @Override
117+ protected Collection<String> getTableDefinitions() {
118+ return Collections.emptyList();
119+ }
120+}
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +4 −0
@@ -45,4 +45,8 @@
4545 return this;
4646 }
4747
48+ public TableMetadataAssert hasMaterializedView(MaterializedViewMetadata expected) {
49+ assertThat(actual.getView(expected.getName())).isNotNull().isEqualTo(expected);
50+ return this;
51+ }
4852 }
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +4 −5
@@ -18,15 +18,14 @@
1818 import java.util.Collection;
1919 import java.util.Collections;
2020
21-import org.testng.SkipException;
2221 import org.testng.annotations.Test;
2322
2423 import static org.assertj.core.api.Assertions.entry;
2524
2625 import static com.datastax.driver.core.Assertions.assertThat;
2726 import static com.datastax.driver.core.DataType.*;
28-import static com.datastax.driver.core.TableMetadata.Order.ASC;
29-import static com.datastax.driver.core.TableMetadata.Order.DESC;
27+import static com.datastax.driver.core.TableOrView.Order.ASC;
28+import static com.datastax.driver.core.TableOrView.Order.DESC;
3029
3130 public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3231
@@ -61,7 +60,7 @@
6160 + " l list<text>,\n"
6261 + " v int,\n"
6362 + " PRIMARY KEY (k, c1, c2)\n"
64- + ");", keyspace);
63+ + ") WITH CLUSTERING ORDER BY (c1 ASC, c2 DESC);", keyspace);
6564 // when
6665 session.execute(cql);
6766 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("sparse");
@@ -69,7 +68,7 @@
6968 assertThat(table).isNotNull().hasName("sparse").hasNumberOfColumns(5).isNotCompactStorage();
7069 assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(text());
7170 assertThat(table.getColumns().get(1)).isNotNull().hasName("c1").isClusteringColumn().hasClusteringOrder(ASC).hasType(cint());
72- assertThat(table.getColumns().get(2)).isNotNull().hasName("c2").isClusteringColumn().hasClusteringOrder(ASC).hasType(cfloat());
71+ assertThat(table.getColumns().get(2)).isNotNull().hasName("c2").isClusteringColumn().hasClusteringOrder(DESC).hasType(cfloat());
7372 assertThat(table.getColumns().get(3)).isNotNull().hasName("l").isRegularColumn().hasType(list(text()));
7473 assertThat(table.getColumns().get(4)).isNotNull().hasName("v").isRegularColumn().hasType(cint());
7574 }