Elffuss BraidHub

kikocis/java-driver public

Merge pull request #429 from datastax/java876

JAVA-876: Support new system tables in C* 3.0.0-alpha1.
Changeset3f051ab69fd7377cc739287c9e3872d1612bbb99c9fc6ef030cce9445c04c5fe
AuthorAlexandre Dutra <alexdut@gmail.com> · 2015-08-11 15:36 +02:00
CommitterAlexandre Dutra <alexdut@gmail.com> · 2015-08-11 15:36 +02:00
Parentsd17d68b5d5a6, 6c829efa72ea

Browse the files at this changeset

14 files changed

modified changelog/README.md +16 −0
@@ -1,5 +1,21 @@
11 ## Changelog
22
3+### 3.0.0-alpha1
4+
5+- [new feature] Support new system tables in C* 3.0.0-alpha1 (JAVA-876)
6+
7+Merged from 2.2 branch:
8+
9+- [improvement] Rename DateWithoutTime to LocalDate (JAVA-810)
10+- [bug] DateCodec does not format values correctly (JAVA-816)
11+- [bug] TimeCodec does not format values correctly (JAVA-817)
12+- [bug] TypeCodec.getDataTypeFor() does not handle LocalDate instances (JAVA-818)
13+- [improvement] Make ResultSet#fetchMoreResult return a
14+ ListenableFuture<ResultSet> (JAVA-836)
15+- [improvement] Disable frozen checks in mapper (JAVA-843)
16+- [improvement] Allow user to register custom type codecs (JAVA-721)
17+- [improvement] Support custom type codecs in mapper (JAVA-722)
18+
319 ### 2.2.0-rc2
420
521 - [improvement] Rename DateWithoutTime to LocalDate (JAVA-810)
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +1 −1
@@ -40,7 +40,7 @@
4040 private final DataType stateType;
4141 private final TypeCodec<Object> stateTypeCodec;
4242
43- public AggregateMetadata(KeyspaceMetadata keyspace, String fullName, String simpleName, List<DataType> argumentTypes,
43+ private AggregateMetadata(KeyspaceMetadata keyspace, String fullName, String simpleName, List<DataType> argumentTypes,
4444 String finalFuncSimpleName, String finalFuncFullName, Object initCond, DataType returnType,
4545 String stateFuncSimpleName, String stateFuncFullName, DataType stateType, TypeCodec<Object> stateTypeCodec) {
4646 this.keyspace = keyspace;
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +2 −2
@@ -2049,7 +2049,7 @@
20492049 if (!schemaInAgreement)
20502050 logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds());
20512051 if (refreshSchema)
2052- ControlConnection.refreshSchema(connection, targetType, targetKeyspace, targetName, targetSignature, Manager.this, false);
2052+ ControlConnection.refreshSchema(connection, targetType, targetKeyspace, targetName, targetSignature, Manager.this);
20532053 } catch (Exception e) {
20542054 if (refreshSchema) {
20552055 logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
@@ -2183,7 +2183,7 @@
21832183 if (scc.targetType == KEYSPACE) {
21842184 manager.metadata.removeKeyspace(scc.targetKeyspace);
21852185 } else {
2186- KeyspaceMetadata keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
2186+ KeyspaceMetadata keyspace = manager.metadata.keyspaces.get(scc.targetKeyspace);
21872187 if (keyspace == null) {
21882188 logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
21892189 scc.targetType, scc.targetKeyspace, scc.targetName);
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +41 −6
@@ -300,10 +300,41 @@
300300 // exposed publicly at all.
301301 static class Raw {
302302
303- public enum Kind { PARTITION_KEY, CLUSTERING_KEY, REGULAR, COMPACT_VALUE, STATIC }
303+ public enum Kind {
304+
305+ PARTITION_KEY ("PARTITION_KEY" , "PARTITION_KEY"),
306+ CLUSTERING_COLUMN ("CLUSTERING_KEY", "CLUSTERING" ),
307+ REGULAR ("REGULAR" , "REGULAR" ),
308+ COMPACT_VALUE ("COMPACT_VALUE" , "" ), // v2 only
309+ STATIC ("STATIC" , "STATIC" );
310+
311+ final String v2;
312+ final String v3;
313+
314+ Kind(String v2, String v3) {
315+ this.v2 = v2;
316+ this.v3 = v3;
317+ }
318+
319+ static Kind fromStringV2(String s) {
320+ for (Kind kind : Kind.values()) {
321+ if(kind.v2.equalsIgnoreCase(s))
322+ return kind;
323+ }
324+ throw new IllegalArgumentException(s);
325+ }
326+
327+ static Kind fromStringV3(String s) {
328+ for (Kind kind : Kind.values()) {
329+ if(kind.v3.equalsIgnoreCase(s))
330+ return kind;
331+ }
332+ throw new IllegalArgumentException(s);
333+ }
334+ }
304335
305336 public final String name;
306- public final Kind kind;
337+ public Kind kind;
307338 public final int componentIndex;
308339 public final DataType dataType;
309340 public final boolean isReversed;
@@ -319,11 +350,15 @@
319350 }
320351
321352 static Raw fromRow(Row row, VersionNumber version, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
322-
323353 String name = row.getString(COLUMN_NAME);
324- Kind kind = version.getMajor() < 2 || row.isNull(KIND)
325- ? Kind.REGULAR
326- : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
354+ Kind kind;
355+ if(version.getMajor() < 2 || row.isNull(KIND)) {
356+ kind = Kind.REGULAR;
357+ } else if (version.getMajor() < 3) {
358+ kind = Kind.fromStringV2(row.getString(KIND));
359+ } else {
360+ kind = Kind.fromStringV3(row.getString(KIND));
361+ }
327362 int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
328363 String validatorStr = row.getString(VALIDATOR);
329364 boolean reversed = CassandraTypeParser.isReversed(validatorStr);
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +9 −84
@@ -32,14 +32,12 @@
3232 import com.datastax.driver.core.exceptions.DriverInternalError;
3333 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3434
35-import static com.datastax.driver.core.SchemaElement.*;
35+import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3636
3737 class ControlConnection {
3838
3939 private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class);
4040
41- private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance);
42-
4341 private static final InetAddress bindAllAddress;
4442 static
4543 {
@@ -50,13 +48,6 @@
5048 }
5149 }
5250
53- private static final String SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces";
54- private static final String SELECT_COLUMN_FAMILIES = "SELECT * FROM system.schema_columnfamilies";
55- private static final String SELECT_COLUMNS = "SELECT * FROM system.schema_columns";
56- private static final String SELECT_USERTYPES = "SELECT * FROM system.schema_usertypes";
57- private static final String SELECT_FUNCTIONS = "SELECT * FROM system.schema_functions";
58- private static final String SELECT_AGGREGATES = "SELECT * FROM system.schema_aggregates";
59-
6051 private static final String SELECT_PEERS = "SELECT * FROM system.peers";
6152 private static final String SELECT_LOCAL = "SELECT * FROM system.local WHERE key='local'";
6253
@@ -270,7 +261,7 @@
270261 // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces
271262 // to be loaded.
272263 logger.debug("[Control connection] Refreshing schema");
273- refreshSchema(connection, null, null, null, null, cluster, isInitialConnection);
264+ refreshSchema(connection, null, null, null, null, cluster);
274265 return connection;
275266 } catch (BusyConnectionException e) {
276267 connection.closeAsync().force();
@@ -299,7 +290,7 @@
299290 // At startup, when we add the initial nodes, this will be null, which is ok
300291 if (c == null)
301292 return;
302- refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster, false);
293+ refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster);
303294 } catch (ConnectionException e) {
304295 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
305296 signalError();
@@ -314,7 +305,7 @@
314305 }
315306 }
316307
317- static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
308+ static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
318309 Host host = cluster.metadata.getHost(connection.address);
319310 // Neither host, nor it's version should be null. But instead of dying if there is a race or something, we can kind of try to infer
320311 // a Cassandra version from the protocol version (this is not full proof, we can have the protocol 1 against C* 2.0+, but it's worth
@@ -328,83 +319,17 @@
328319 cassandraVersion = host.getCassandraVersion();
329320 }
330321
331- // Make sure we're up to date on schema
332- String whereClause = "";
333- if (targetType != null) {
334- whereClause = " WHERE keyspace_name = '" + targetKeyspace + '\'';
335- if (targetType == TABLE)
336- whereClause += " AND columnfamily_name = '" + targetName + '\'';
337- else if (targetType == TYPE)
338- whereClause += " AND type_name = '" + targetName + '\'';
339- else if (targetType == FUNCTION)
340- whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
341- else if (targetType == AGGREGATE)
342- whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
343- }
344-
345- boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
346- DefaultResultSetFuture ksFuture = isSchemaOrKeyspace
347- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_KEYSPACES + whereClause))
348- : null;
349- DefaultResultSetFuture udtFuture = (isSchemaOrKeyspace && supportsUdts(cassandraVersion) || targetType == TYPE)
350- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_USERTYPES + whereClause))
351- : null;
352- DefaultResultSetFuture cfFuture = (isSchemaOrKeyspace || targetType == TABLE)
353- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMN_FAMILIES + whereClause))
354- : null;
355- DefaultResultSetFuture colsFuture = (isSchemaOrKeyspace || targetType == TABLE)
356- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_COLUMNS + whereClause))
357- : null;
358- DefaultResultSetFuture functionsFuture = (isSchemaOrKeyspace && supportsUdfs(cassandraVersion) || targetType == FUNCTION)
359- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_FUNCTIONS + whereClause))
360- : null;
361- DefaultResultSetFuture aggregatesFuture = (isSchemaOrKeyspace && supportsUdfs(cassandraVersion) || targetType == AGGREGATE)
362- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_AGGREGATES + whereClause))
363- : null;
364-
365- if (ksFuture != null)
366- connection.write(ksFuture);
367- if (udtFuture != null)
368- connection.write(udtFuture);
369- if (cfFuture != null)
370- connection.write(cfFuture);
371- if (colsFuture != null)
372- connection.write(colsFuture);
373- if (functionsFuture != null)
374- connection.write(functionsFuture);
375- if (aggregatesFuture != null)
376- connection.write(aggregatesFuture);
377-
378- try {
379- cluster.metadata.rebuildSchema(targetType, targetKeyspace, targetName,
380- ksFuture == null ? null : ksFuture.get(),
381- udtFuture == null ? null : udtFuture.get(),
382- cfFuture == null ? null : cfFuture.get(),
383- colsFuture == null ? null : colsFuture.get(),
384- functionsFuture == null ? null : functionsFuture.get(),
385- aggregatesFuture == null ? null : aggregatesFuture.get(),
386- cassandraVersion);
387- } catch (RuntimeException e) {
388- // Failure to parse the schema is definitively wrong so log a full-on error, but this won't generally prevent queries to
389- // work and this can happen when new Cassandra versions modify stuff in the schema and the driver hasn't yet be modified.
390- // So log, but let things go otherwise.
391- logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e);
392- }
322+ SchemaParser.forVersion(cassandraVersion)
323+ .refresh(cluster.metadata,
324+ targetType, targetKeyspace, targetName, targetSignature,
325+ connection, cassandraVersion);
393326
394327 // If we rebuild all from scratch or have an updated keyspace, rebuild the token map since some replication on some keyspace
395328 // may have changed
396- if (isSchemaOrKeyspace)
329+ if ((targetType == null || targetType == KEYSPACE))
397330 refreshNodeListAndTokenMap(connection, cluster, false, false);
398331 }
399332
400- private static boolean supportsUdts(VersionNumber cassandraVersion) {
401- return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1);
402- }
403-
404- private static boolean supportsUdfs(VersionNumber cassandraVersion) {
405- return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 2);
406- }
407-
408333 public void refreshNodeListAndTokenMap() {
409334 Connection c = connectionRef.get();
410335 // At startup, when we add the initial nodes, this will be null, which is ok
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −3
@@ -27,8 +27,6 @@
2727 import com.datastax.driver.core.exceptions.*;
2828
2929 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
30-import static com.datastax.driver.core.SchemaElement.TABLE;
31-import static com.datastax.driver.core.SchemaElement.TYPE;
3230
3331 /**
3432 * Internal implementation of ResultSetFuture.
@@ -83,7 +81,7 @@
8381 if (scc.targetType == KEYSPACE) {
8482 session.cluster.manager.metadata.removeKeyspace(scc.targetKeyspace);
8583 } else {
86- KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
84+ KeyspaceMetadata keyspace = session.cluster.manager.metadata.keyspaces.get(scc.targetKeyspace);
8785 if (keyspace == null) {
8886 logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
8987 scc.targetType, scc.targetKeyspace, scc.targetName);
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +19 −21
@@ -15,7 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
18+import java.util.Collection;
19+import java.util.Collections;
20+import java.util.HashMap;
21+import java.util.Map;
1922 import java.util.concurrent.ConcurrentHashMap;
2023
2124 import com.google.common.annotations.VisibleForTesting;
@@ -26,10 +29,11 @@
2629 */
2730 public class KeyspaceMetadata {
2831
29- public static final String KS_NAME = "keyspace_name";
32+ public static final String KS_NAME = "keyspace_name";
3033 private static final String DURABLE_WRITES = "durable_writes";
3134 private static final String STRATEGY_CLASS = "strategy_class";
3235 private static final String STRATEGY_OPTIONS = "strategy_options";
36+ private static final String REPLICATION = "replication";
3337
3438 private final String name;
3539 private final boolean durableWrites;
@@ -50,23 +54,20 @@
5054 this.strategy = ReplicationStrategy.create(replication);
5155 }
5256
53- static KeyspaceMetadata build(Row row, List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
54-
57+ static KeyspaceMetadata buildV2(Row row) {
5558 String name = row.getString(KS_NAME);
5659 boolean durableWrites = row.getBool(DURABLE_WRITES);
57-
58- Map<String, String> replicationOptions = new HashMap<String, String>();
60+ Map<String, String> replicationOptions;
61+ replicationOptions = new HashMap<String, String>();
5962 replicationOptions.put("class", row.getString(STRATEGY_CLASS));
6063 replicationOptions.putAll(SimpleJSONParser.parseStringMap(row.getString(STRATEGY_OPTIONS)));
64+ return new KeyspaceMetadata(name, durableWrites, replicationOptions);
65+ }
6166
62- KeyspaceMetadata ksm = new KeyspaceMetadata(name, durableWrites, replicationOptions);
63-
64- if (udtRows == null)
65- return ksm;
66-
67- ksm.addUserTypes(udtRows, protocolVersion, codecRegistry);
68-
69- return ksm;
67+ static KeyspaceMetadata buildV3(Row row) {
68+ String name = row.getString(KS_NAME);
69+ boolean durableWrites = row.getBool(DURABLE_WRITES);
70+ return new KeyspaceMetadata(name, durableWrites, row.getMap(REPLICATION, String.class, String.class));
7071 }
7172
7273 /**
@@ -143,13 +144,6 @@
143144 return Collections.unmodifiableCollection(userTypes.values());
144145 }
145146
146- void addUserTypes(List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
147- for (Row r : udtRows) {
148- UserType def = UserType.build(r, protocolVersion, codecRegistry);
149- userTypes.put(def.getTypeName(), def);
150- }
151- }
152-
153147 void removeUserType(String userType) {
154148 userTypes.remove(userType);
155149 }
@@ -305,6 +299,10 @@
305299 aggregates.put(aggregate.getFullName(), aggregate);
306300 }
307301
302+ void add(UserType userType) {
303+ userTypes.put(userType.getTypeName(), userType);
304+ }
305+
308306 ReplicationStrategy replicationStrategy() {
309307 return strategy;
310308 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +17 −182
@@ -20,33 +20,30 @@
2020 import java.util.*;
2121 import java.util.concurrent.ConcurrentHashMap;
2222 import java.util.concurrent.ConcurrentMap;
23+import java.util.concurrent.locks.ReentrantLock;
2324 import java.util.regex.Pattern;
2425
2526 import com.google.common.base.Joiner;
2627 import com.google.common.collect.ImmutableMap;
2728 import com.google.common.collect.ImmutableSet;
2829 import com.google.common.collect.Maps;
29-import org.slf4j.Logger;
30-import org.slf4j.LoggerFactory;
3130
3231 import com.datastax.driver.core.exceptions.DriverInternalError;
3332
34-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
35-
3633 /**
3734 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3835 */
3936 public class Metadata {
4037
41- private static final Logger logger = LoggerFactory.getLogger(Metadata.class);
42-
43- private final Cluster.Manager cluster;
38+ final Cluster.Manager cluster;
4439 volatile String clusterName;
4540 volatile String partitioner;
4641 private final ConcurrentMap<InetSocketAddress, Host> hosts = new ConcurrentHashMap<InetSocketAddress, Host>();
47- private final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>();
42+ final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>();
4843 volatile TokenMap tokenMap;
4944
45+ final ReentrantLock lock = new ReentrantLock();
46+
5047 private static final Pattern cqlId = Pattern.compile("\\w+");
5148 private static final Pattern lowercaseId = Pattern.compile("[a-z][a-z0-9_]*");
5249
@@ -54,176 +51,22 @@
5451 this.cluster = cluster;
5552 }
5653
57- // Synchronized to make it easy to detect dropped keyspaces
58- synchronized void rebuildSchema(SchemaElement targetType, String targetKeyspace, String targetName,
59- ResultSet ks, ResultSet udts, ResultSet cfs,
60- ResultSet cols, ResultSet functions, ResultSet aggregates,
61- VersionNumber cassandraVersion) {
62-
63-
64- Map<String, List<Row>> udtDefs = groupByKeyspace(udts);
65- Map<String, List<Row>> cfDefs = groupByKeyspace(cfs);
66- Map<String, List<Row>> functionDefs = groupByKeyspace(functions);
67- Map<String, List<Row>> aggregateDefs = groupByKeyspace(aggregates);
68-
69- // Gather columns per Cf
70- Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
71- if (cols != null) {
72- for (Row row : cols) {
73- String ksName = row.getString(KeyspaceMetadata.KS_NAME);
74- String cfName = row.getString(TableMetadata.CF_NAME);
75- Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = colsDefs.get(ksName);
76- if (colsByCf == null) {
77- colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>();
78- colsDefs.put(ksName, colsByCf);
79- }
80- Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName);
81- if (l == null) {
82- l = new HashMap<String, ColumnMetadata.Raw>();
83- colsByCf.put(cfName, l);
84- }
85- ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
86- l.put(c.name, c);
87- }
88- }
89-
90- if (targetType == null || targetType == KEYSPACE) { // Refresh one or all keyspaces
91- assert ks != null;
92- Set<String> addedKs = new HashSet<String>();
93- for (Row ksRow : ks) {
94- String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME);
95- KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow, udtDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
96-
97- if (cfDefs.containsKey(ksName)) {
98- buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion);
99- }
100- if (functionDefs.containsKey(ksName)) {
101- buildFunctionMetadata(ksm, functionDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
102- }
103- if (aggregateDefs.containsKey(ksName)) {
104- buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
105- }
106- addedKs.add(ksName);
107- keyspaces.put(ksName, ksm);
108- }
109-
110- // If keyspace is null, it means we're rebuilding from scratch, so
111- // remove anything that was not just added as it means it's a dropped keyspace
112- if (targetKeyspace == null) {
113- Iterator<String> iter = keyspaces.keySet().iterator();
114- while (iter.hasNext()) {
115- if (!addedKs.contains(iter.next()))
116- iter.remove();
117- }
118- }
119- } else {
120- assert targetKeyspace != null;
121- KeyspaceMetadata ksm = keyspaces.get(targetKeyspace);
122-
123- // If we update a keyspace we don't know about, something went
124- // wrong. Log an error an schedule a full schema rebuilt.
125- if (ksm == null) {
126- logger.error(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s", targetType, targetKeyspace, targetName, targetKeyspace));
127- cluster.submitSchemaRefresh(null, null, null, null);
54+ void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) {
55+ lock.lock();
56+ try {
57+ if (allTokens.isEmpty())
12858 return;
129- }
130-
131- switch (targetType) {
132- case TABLE:
133- if (cfDefs.containsKey(targetKeyspace))
134- buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion);
135- break;
136- case TYPE:
137- if (udtDefs.containsKey(targetKeyspace))
138- ksm.addUserTypes(udtDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
139- break;
140- case FUNCTION:
141- if (functionDefs.containsKey(targetKeyspace))
142- buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
143- break;
144- case AGGREGATE:
145- if (functionDefs.containsKey(targetKeyspace))
146- buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
147- break;
148- default:
149- logger.warn("Unexpected element type to rebuild: {}", targetType);
150- }
151- }
152- }
153-
154- private Map<String, List<Row>> groupByKeyspace(ResultSet rs) {
155- if (rs == null)
156- return Collections.emptyMap();
157-
158- Map<String, List<Row>> result = new HashMap<String, List<Row>>();
159- for (Row row : rs) {
160- String ksName = row.getString(KeyspaceMetadata.KS_NAME);
161- List<Row> l = result.get(ksName);
162- if (l == null) {
163- l = new ArrayList<Row>();
164- result.put(ksName, l);
165- }
166- l.add(row);
167- }
168- return result;
169- }
170-
171- private void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
172- for (Row cfRow : cfRows) {
173- String cfName = cfRow.getString(TableMetadata.CF_NAME);
174- try {
175- Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName);
176- if (cols == null || cols.isEmpty()) {
177- if (cassandraVersion.getMajor() >= 2) {
178- // In C* >= 2.0, we should never have no columns metadata because at the very least we should
179- // have the metadata corresponding to the default CQL metadata. So if we don't have any columns,
180- // that can only mean that the table got creating concurrently with our schema queries, and the
181- // query for columns metadata reached the node before the table was persisted while the table
182- // metadata one reached it afterwards. We could make the query to the column metadata sequential
183- // with the table metadata instead of in parallel, but it's probably not worth making it slower
184- // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the
185- // incomplete table here for now and it'll get updated next time with no particular consequence
186- // (if the table creation was concurrent with our querying, we'll get a notifciation later and
187- // will reupdate the schema for it anyway). See JAVA-320 for why we need this.
188- continue;
189- } else {
190- // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft
191- // tables). But in that case TableMetadata.build() knows how to handle it.
192- cols = Collections.<String, ColumnMetadata.Raw>emptyMap();
193- }
194- }
195- TableMetadata.build(ksm, cfRow, cols, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
196- } catch (RuntimeException e) {
197- // See ControlConnection#refreshSchema for why we'd rather not probably this further
198- logger.error(String.format("Error parsing schema for table %s.%s: "
199- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
200- ksm.getName(), cfName, ksm.getName(), cfName), e);
201- }
202- }
203- }
204-
205- private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
206- for (Row row : rows)
207- FunctionMetadata.build(ksm, row, protocolVersion, codecRegistry);
208- }
209-
210- private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
211- for (Row row : rows)
212- AggregateMetadata.build(ksm, row, protocolVersion, codecRegistry);
213- }
214-
21559
216- synchronized void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) {
217- if (allTokens.isEmpty())
218- return;
219-
220- Token.Factory factory = partitioner == null
221- ? (tokenMap == null ? null : tokenMap.factory)
222- : Token.getFactory(partitioner);
223- if (factory == null)
224- return;
60+ Token.Factory factory = partitioner == null
61+ ? (tokenMap == null ? null : tokenMap.factory)
62+ : Token.getFactory(partitioner);
63+ if (factory == null)
64+ return;
22565
22666 this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
67+ } finally {
68+ lock.unlock();
69+ }
22770 }
22871
22972 Host add(InetSocketAddress address) {
@@ -440,14 +283,6 @@
440283 return keyspaces.get(handleId(keyspace));
441284 }
442285
443- /**
444- * Used when the keyspace name is unquoted and in the exact case we store it in
445- * (typically when we got it from an internal call, not from the user).
446- */
447- KeyspaceMetadata getKeyspaceInternal(String keyspace) {
448- return keyspaces.get(keyspace);
449- }
450-
451286 void removeKeyspace(String keyspace) {
452287 keyspaces.remove(keyspace);
453288 if (tokenMap != null)
added driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +428 −0
@@ -0,0 +1,428 @@
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+import java.util.concurrent.ExecutionException;
20+
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+
24+import static com.datastax.driver.core.SchemaElement.*;
25+
26+abstract class SchemaParser {
27+
28+ private static final Logger logger = LoggerFactory.getLogger(SchemaParser.class);
29+
30+ private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance);
31+
32+ static SchemaParser forVersion(VersionNumber cassandraVersion) {
33+ if(cassandraVersion.getMajor() >= 3) return V3_PARSER;
34+ return V2_PARSER;
35+ }
36+
37+ abstract void refresh(Metadata metadata,
38+ SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
39+ Connection connection, VersionNumber cassandraVersion)
40+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException;
41+
42+ private static SchemaParser V2_PARSER = new SchemaParser() {
43+
44+ private static final String SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces";
45+ private static final String SELECT_COLUMN_FAMILIES = "SELECT * FROM system.schema_columnfamilies";
46+ private static final String SELECT_COLUMNS = "SELECT * FROM system.schema_columns";
47+ private static final String SELECT_USERTYPES = "SELECT * FROM system.schema_usertypes";
48+ private static final String SELECT_FUNCTIONS = "SELECT * FROM system.schema_functions";
49+ private static final String SELECT_AGGREGATES = "SELECT * FROM system.schema_aggregates";
50+
51+ private static final String CF_NAME = "columnfamily_name";
52+
53+ @Override
54+ void refresh(Metadata metadata,
55+ SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
56+ Connection connection, VersionNumber cassandraVersion)
57+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
58+
59+ boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
60+ ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
61+ CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
62+
63+ String whereClause = "";
64+ if (targetType != null) {
65+ whereClause = " WHERE keyspace_name = '" + targetKeyspace + '\'';
66+ if (targetType == TABLE)
67+ whereClause += " AND columnfamily_name = '" + targetName + '\'';
68+ else if (targetType == TYPE)
69+ whereClause += " AND type_name = '" + targetName + '\'';
70+ else if (targetType == FUNCTION)
71+ whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
72+ else if (targetType == AGGREGATE)
73+ whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
74+ }
75+
76+ ResultSetFuture ksFuture = null,
77+ udtFuture = null,
78+ cfFuture = null,
79+ colsFuture = null,
80+ functionsFuture = null,
81+ aggregatesFuture = null;
82+
83+ if (isSchemaOrKeyspace)
84+ ksFuture = queryAsync(SELECT_KEYSPACES + whereClause, connection, protocolVersion);
85+
86+ if (isSchemaOrKeyspace && supportsUdts(cassandraVersion) || targetType == TYPE)
87+ udtFuture = queryAsync(SELECT_USERTYPES + whereClause, connection, protocolVersion);
88+
89+ if (isSchemaOrKeyspace || targetType == TABLE) {
90+ cfFuture = queryAsync(SELECT_COLUMN_FAMILIES + whereClause, connection, protocolVersion);
91+ colsFuture = queryAsync(SELECT_COLUMNS + whereClause, connection, protocolVersion);
92+ }
93+
94+ if ((isSchemaOrKeyspace && supportsUdfs(cassandraVersion) || targetType == FUNCTION))
95+ functionsFuture = queryAsync(SELECT_FUNCTIONS + whereClause, connection, protocolVersion);
96+
97+ if (isSchemaOrKeyspace && supportsUdfs(cassandraVersion) || targetType == AGGREGATE)
98+ aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause, connection, protocolVersion);
99+
100+ ResultSet ks = get(ksFuture);
101+ Map<String, List<Row>> udtDefs = groupByKeyspace(get(udtFuture));
102+ Map<String, List<Row>> cfDefs = groupByKeyspace(get(cfFuture));
103+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
104+ Map<String, List<Row>> functionDefs = groupByKeyspace(get(functionsFuture));
105+ Map<String, List<Row>> aggregateDefs = groupByKeyspace(get(aggregatesFuture));
106+
107+ metadata.lock.lock();
108+ try {
109+ if (targetType == null || targetType == KEYSPACE) { // Refresh one or all keyspaces
110+ assert ks != null;
111+ Set<String> addedKs = new HashSet<String>();
112+ for (Row ksRow : ks) {
113+ String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME);
114+ KeyspaceMetadata ksm = KeyspaceMetadata.buildV2(ksRow);
115+
116+ if (udtDefs.containsKey(ksName)) {
117+ buildUserTypes(ksm, udtDefs.get(ksName), protocolVersion, codecRegistry);
118+ }
119+ if (cfDefs.containsKey(ksName)) {
120+ buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
121+ }
122+ if (functionDefs.containsKey(ksName)) {
123+ buildFunctionMetadata(ksm, functionDefs.get(ksName), protocolVersion, codecRegistry);
124+ }
125+ if (aggregateDefs.containsKey(ksName)) {
126+ buildAggregateMetadata(ksm, aggregateDefs.get(ksName), protocolVersion, codecRegistry);
127+ }
128+ addedKs.add(ksName);
129+ metadata.keyspaces.put(ksName, ksm);
130+ }
131+
132+ // If keyspace is null, it means we're rebuilding from scratch, so
133+ // remove anything that was not just added as it means it's a dropped keyspace
134+ if (targetKeyspace == null) {
135+ Iterator<String> iter = metadata.keyspaces.keySet().iterator();
136+ while (iter.hasNext()) {
137+ if (!addedKs.contains(iter.next()))
138+ iter.remove();
139+ }
140+ }
141+ } else {
142+ assert targetKeyspace != null;
143+ KeyspaceMetadata ksm = metadata.keyspaces.get(targetKeyspace);
144+
145+ // If we update a keyspace we don't know about, something went
146+ // wrong. Log an error an schedule a full schema rebuilt.
147+ if (ksm == null) {
148+ logger.error(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s", targetType, targetKeyspace, targetName, targetKeyspace));
149+ metadata.cluster.submitSchemaRefresh(null, null, null, null);
150+ return;
151+ }
152+
153+ switch (targetType) {
154+ case TABLE:
155+ if (cfDefs.containsKey(targetKeyspace))
156+ buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, CF_NAME);
157+ break;
158+ case TYPE:
159+ if (udtDefs.containsKey(targetKeyspace))
160+ buildUserTypes(ksm, udtDefs.get(targetKeyspace), protocolVersion, codecRegistry);
161+ break;
162+ case FUNCTION:
163+ if (functionDefs.containsKey(targetKeyspace))
164+ buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), protocolVersion, codecRegistry);
165+ break;
166+ case AGGREGATE:
167+ if (functionDefs.containsKey(targetKeyspace))
168+ buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), protocolVersion, codecRegistry);
169+ break;
170+ default:
171+ logger.warn("Unexpected element type to rebuild: {}", targetType);
172+ }
173+ }
174+ } finally {
175+ metadata.lock.unlock();
176+ }
177+ }
178+
179+ private boolean supportsUdts(VersionNumber cassandraVersion) {
180+ return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1);
181+ }
182+
183+ private boolean supportsUdfs(VersionNumber cassandraVersion) {
184+ return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 2);
185+ }
186+
187+ };
188+
189+ private static SchemaParser V3_PARSER = new SchemaParser() {
190+
191+ private static final String SELECT_KEYSPACES = "SELECT * FROM system_schema.keyspaces";
192+ private static final String SELECT_TABLES = "SELECT * FROM system_schema.tables";
193+ private static final String SELECT_COLUMNS = "SELECT * FROM system_schema.columns";
194+ private static final String SELECT_USERTYPES = "SELECT * FROM system_schema.types";
195+ private static final String SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions";
196+ private static final String SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates";
197+
198+ private static final String TABLE_NAME = "table_name";
199+
200+ @Override
201+ void refresh(Metadata metadata,
202+ SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
203+ Connection connection, VersionNumber cassandraVersion)
204+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
205+
206+ boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
207+ ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
208+ CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
209+
210+ String whereClause = "";
211+ if (targetType != null) {
212+ whereClause = " WHERE keyspace_name = '" + targetKeyspace + '\'';
213+ if (targetType == TABLE)
214+ whereClause += " AND table_name = '" + targetName + '\'';
215+ else if (targetType == TYPE)
216+ whereClause += " AND type_name = '" + targetName + '\'';
217+ else if (targetType == FUNCTION)
218+ whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
219+ else if (targetType == AGGREGATE)
220+ whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
221+ }
222+
223+ ResultSetFuture ksFuture = null,
224+ udtFuture = null,
225+ cfFuture = null,
226+ colsFuture = null,
227+ functionsFuture = null,
228+ aggregatesFuture = null;
229+
230+ if (isSchemaOrKeyspace)
231+ ksFuture = queryAsync(SELECT_KEYSPACES + whereClause, connection, protocolVersion);
232+
233+ if (isSchemaOrKeyspace || targetType == TYPE)
234+ udtFuture = queryAsync(SELECT_USERTYPES + whereClause, connection, protocolVersion);
235+
236+ if (isSchemaOrKeyspace || targetType == TABLE) {
237+ cfFuture = queryAsync(SELECT_TABLES + whereClause, connection, protocolVersion);
238+ colsFuture = queryAsync(SELECT_COLUMNS + whereClause, connection, protocolVersion);
239+ }
240+
241+ if ((isSchemaOrKeyspace || targetType == FUNCTION))
242+ functionsFuture = queryAsync(SELECT_FUNCTIONS + whereClause, connection, protocolVersion);
243+
244+ if (isSchemaOrKeyspace || targetType == AGGREGATE)
245+ aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause, connection, protocolVersion);
246+
247+ ResultSet ks = get(ksFuture);
248+ Map<String, List<Row>> udtDefs = groupByKeyspace(get(udtFuture));
249+ Map<String, List<Row>> cfDefs = groupByKeyspace(get(cfFuture));
250+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
251+ Map<String, List<Row>> functionDefs = groupByKeyspace(get(functionsFuture));
252+ Map<String, List<Row>> aggregateDefs = groupByKeyspace(get(aggregatesFuture));
253+
254+ metadata.lock.lock();
255+ try {
256+ if (targetType == null || targetType == KEYSPACE) { // Refresh one or all keyspaces
257+ assert ks != null;
258+ Set<String> addedKs = new HashSet<String>();
259+ for (Row ksRow : ks) {
260+ String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME);
261+ KeyspaceMetadata ksm = KeyspaceMetadata.buildV3(ksRow);
262+
263+ if (udtDefs.containsKey(ksName)) {
264+ buildUserTypes(ksm, udtDefs.get(ksName), protocolVersion, codecRegistry);
265+ }
266+ if (cfDefs.containsKey(ksName)) {
267+ buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
268+ }
269+ if (functionDefs.containsKey(ksName)) {
270+ buildFunctionMetadata(ksm, functionDefs.get(ksName), protocolVersion, codecRegistry);
271+ }
272+ if (aggregateDefs.containsKey(ksName)) {
273+ buildAggregateMetadata(ksm, aggregateDefs.get(ksName), protocolVersion, codecRegistry);
274+ }
275+ addedKs.add(ksName);
276+ metadata.keyspaces.put(ksName, ksm);
277+ }
278+
279+ // If keyspace is null, it means we're rebuilding from scratch, so
280+ // remove anything that was not just added as it means it's a dropped keyspace
281+ if (targetKeyspace == null) {
282+ Iterator<String> iter = metadata.keyspaces.keySet().iterator();
283+ while (iter.hasNext()) {
284+ if (!addedKs.contains(iter.next()))
285+ iter.remove();
286+ }
287+ }
288+ } else {
289+ assert targetKeyspace != null;
290+ KeyspaceMetadata ksm = metadata.keyspaces.get(targetKeyspace);
291+
292+ // If we update a keyspace we don't know about, something went
293+ // wrong. Log an error an schedule a full schema rebuilt.
294+ if (ksm == null) {
295+ logger.error(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s", targetType, targetKeyspace, targetName, targetKeyspace));
296+ metadata.cluster.submitSchemaRefresh(null, null, null, null);
297+ return;
298+ }
299+
300+ switch (targetType) {
301+ case TABLE:
302+ if (cfDefs.containsKey(targetKeyspace))
303+ buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME);
304+ break;
305+ case TYPE:
306+ if (udtDefs.containsKey(targetKeyspace))
307+ buildUserTypes(ksm, udtDefs.get(targetKeyspace), protocolVersion, codecRegistry);
308+ break;
309+ case FUNCTION:
310+ if (functionDefs.containsKey(targetKeyspace))
311+ buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), protocolVersion, codecRegistry);
312+ break;
313+ case AGGREGATE:
314+ if (functionDefs.containsKey(targetKeyspace))
315+ buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), protocolVersion, codecRegistry);
316+ break;
317+ default:
318+ logger.warn("Unexpected element type to rebuild: {}", targetType);
319+ }
320+ }
321+ } finally {
322+ metadata.lock.unlock();
323+ }
324+ }
325+ };
326+
327+ static void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
328+ for (Row cfRow : cfRows) {
329+ String cfName = cfRow.getString(tableName);
330+ try {
331+ Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName);
332+ if (cols == null || cols.isEmpty()) {
333+ if (cassandraVersion.getMajor() >= 2) {
334+ // In C* >= 2.0, we should never have no columns metadata because at the very least we should
335+ // have the metadata corresponding to the default CQL metadata. So if we don't have any columns,
336+ // that can only mean that the table got creating concurrently with our schema queries, and the
337+ // query for columns metadata reached the node before the table was persisted while the table
338+ // metadata one reached it afterwards. We could make the query to the column metadata sequential
339+ // with the table metadata instead of in parallel, but it's probably not worth making it slower
340+ // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the
341+ // incomplete table here for now and it'll get updated next time with no particular consequence
342+ // (if the table creation was concurrent with our querying, we'll get a notifciation later and
343+ // will reupdate the schema for it anyway). See JAVA-320 for why we need this.
344+ continue;
345+ } else {
346+ // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thrift
347+ // tables). But in that case TableMetadata.build() knows how to handle it.
348+ cols = Collections.emptyMap();
349+ }
350+ }
351+ ksm.add(TableMetadata.build(ksm, cfRow, cols, tableName, cassandraVersion, protocolVersion, codecRegistry));
352+ } catch (RuntimeException e) {
353+ // See ControlConnection#refreshSchema for why we'd rather not probably this further
354+ logger.error(String.format("Error parsing schema for table %s.%s: "
355+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
356+ ksm.getName(), cfName, ksm.getName(), cfName), e);
357+ }
358+ }
359+ }
360+
361+ static void buildUserTypes(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
362+ for (Row row : rows)
363+ ksm.add(UserType.build(row, protocolVersion, codecRegistry));
364+ }
365+
366+ static void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
367+ for (Row row : rows)
368+ ksm.add(FunctionMetadata.build(ksm, row, protocolVersion, codecRegistry));
369+ }
370+
371+ static void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
372+ for (Row row : rows)
373+ ksm.add(AggregateMetadata.build(ksm, row, protocolVersion, codecRegistry));
374+ }
375+
376+ static Map<String, List<Row>> groupByKeyspace(ResultSet rs) {
377+ if (rs == null)
378+ return Collections.emptyMap();
379+
380+ Map<String, List<Row>> result = new HashMap<String, List<Row>>();
381+ for (Row row : rs) {
382+ String ksName = row.getString(KeyspaceMetadata.KS_NAME);
383+ List<Row> l = result.get(ksName);
384+ if (l == null) {
385+ l = new ArrayList<Row>();
386+ result.put(ksName, l);
387+ }
388+ l.add(row);
389+ }
390+ return result;
391+ }
392+
393+ static Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndCf(ResultSet rs, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
394+ if (rs == null)
395+ return Collections.emptyMap();
396+
397+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> result =
398+ new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
399+ for (Row row : rs) {
400+ String ksName = row.getString(KeyspaceMetadata.KS_NAME);
401+ String cfName = row.getString(tableName);
402+ Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = result.get(ksName);
403+ if (colsByCf == null) {
404+ colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>();
405+ result.put(ksName, colsByCf);
406+ }
407+ Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName);
408+ if (l == null) {
409+ l = new HashMap<String, ColumnMetadata.Raw>();
410+ colsByCf.put(cfName, l);
411+ }
412+ ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, protocolVersion, codecRegistry);
413+ l.put(c.name, c);
414+ }
415+ return result;
416+ }
417+
418+ private static ResultSetFuture queryAsync(String query, Connection connection, ProtocolVersion protocolVersion) throws ConnectionException, BusyConnectionException {
419+ DefaultResultSetFuture future = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query(query));
420+ connection.write(future);
421+ return future;
422+ }
423+
424+ private static ResultSet get(ResultSetFuture future) throws InterruptedException, ExecutionException {
425+ return (future == null) ? null : future.get();
426+ }
427+
428+}
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +192 −50
@@ -30,8 +30,8 @@
3030
3131 private static final Logger logger = LoggerFactory.getLogger(TableMetadata.class);
3232
33- static final String CF_NAME = "columnfamily_name";
34- private static final String CF_ID = "cf_id";
33+ private static final String CF_ID_V2 = "cf_id";
34+ private static final String CF_ID_V3 = "id";
3535
3636 private static final String KEY_VALIDATOR = "key_validator";
3737 private static final String COMPARATOR = "comparator";
@@ -45,6 +45,13 @@
4545 private static final String DEFAULT_COLUMN_ALIAS = "column";
4646 private static final String DEFAULT_VALUE_ALIAS = "value";
4747
48+ private static final String FLAGS = "flags";
49+ private static final String DENSE = "dense";
50+ private static final String SUPER = "super";
51+ private static final String COMPOUND = "compound";
52+
53+ private static final String EMPTY_TYPE = "org.apache.cassandra.db.marshal.EmptyType";
54+
4855 private static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
4956 public int compare(ColumnMetadata c1, ColumnMetadata c2) {
5057 return c1.getName().compareTo(c2.getName());
@@ -98,30 +105,65 @@
98105 this.cassandraVersion = cassandraVersion;
99106 }
100107
101- static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
108+ static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, String nameColumn, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
109+
110+ String name = row.getString(nameColumn);
111+
112+ UUID id = null;
113+
114+ if(cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)
115+ id = row.getUUID(CF_ID_V2);
116+ else if(cassandraVersion.getMajor() > 2)
117+ id = row.getUUID(CF_ID_V3);
102118
103- String name = row.getString(CF_NAME);
104- UUID id = (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1))
105- ? row.getUUID(CF_ID)
106- : null;
119+ CassandraTypeParser.ParseResult comparator = null;
120+ CassandraTypeParser.ParseResult keyValidator = null;
121+ List<String> columnAliases = null;
107122
108- CassandraTypeParser.ParseResult keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
109- CassandraTypeParser.ParseResult comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
110- List<String> columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
111- ? Collections.<String>emptyList()
112- : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
123+ if(cassandraVersion.getMajor() <= 2) {
124+ comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
125+ keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
126+ columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
127+ ? Collections.<String>emptyList()
128+ : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
129+ }
113130
114- int clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
115- boolean isDense = clusteringSize != comparator.types.size() - 1;
116- boolean isCompact = isDense || !comparator.isComposite;
131+ int partitionKeySize = findPartitionKeySize(rawCols.values(), keyValidator);
132+ int clusteringSize;
133+
134+ boolean isDense;
135+ boolean isCompact;
136+ if(cassandraVersion.getMajor() > 2) {
137+ Set<String> flags = row.getSet(FLAGS, String.class);
138+ isDense = flags.contains(DENSE);
139+ boolean isSuper = flags.contains(SUPER);
140+ boolean isCompound = flags.contains(COMPOUND);
141+ isCompact = isSuper || isDense || !isCompound;
142+ boolean isStaticCompact = !isSuper && !isDense && !isCompound;
143+ if(isStaticCompact) {
144+ rawCols = pruneStaticCompactTableColumns(rawCols);
145+ }
146+ if(isDense) {
147+ rawCols = pruneDenseTableColumnsV3(rawCols);
148+ }
149+ clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
150+ } else {
151+ assert comparator != null;
152+ clusteringSize = findClusteringSize(comparator, rawCols.values(), columnAliases, cassandraVersion);
153+ isDense = clusteringSize != comparator.types.size() - 1;
154+ if(isDense) {
155+ rawCols = pruneDenseTableColumnsV2(rawCols);
156+ }
157+ isCompact = isDense || !comparator.isComposite;
158+ }
117159
118- List<ColumnMetadata> partitionKey = nullInitializedList(keyValidator.types.size());
160+ List<ColumnMetadata> partitionKey = nullInitializedList(partitionKeySize);
119161 List<ColumnMetadata> clusteringColumns = nullInitializedList(clusteringSize);
120162 List<Order> clusteringOrder = nullInitializedList(clusteringSize);
163+
121164 // We use a linked hashmap because we will keep this in the order of a 'SELECT * FROM ...'.
122165 LinkedHashMap<String, ColumnMetadata> columns = new LinkedHashMap<String, ColumnMetadata>();
123166
124-
125167 Options options = null;
126168 try {
127169 options = new Options(row, isCompact, cassandraVersion);
@@ -140,6 +182,11 @@
140182 Set<ColumnMetadata> otherColumns = new TreeSet<ColumnMetadata>(columnMetadataComparator);
141183
142184 if (cassandraVersion.getMajor() < 2) {
185+
186+ assert comparator != null;
187+ assert keyValidator != null;
188+ assert columnAliases != null;
189+
143190 // In C* 1.2, only the REGULAR columns are in the columns schema table, so we need to add the names from
144191 // the aliases (and make sure we handle default aliases).
145192 List<String> keyAliases = row.getString(KEY_ALIASES) == null
@@ -156,11 +203,14 @@
156203 clusteringOrder.set(i, comparator.reversed.get(i) ? Order.DESC : Order.ASC);
157204 }
158205
159- // We have a value alias if we're dense
206+ // if we're dense, chances are that we have a single regular "value" column with an alias
160207 if (isDense) {
161208 String alias = row.isNull(VALUE_ALIAS) ? DEFAULT_VALUE_ALIAS : row.getString(VALUE_ALIAS);
162- DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
163- otherColumns.add(ColumnMetadata.forAlias(tm, alias, type));
209+ // ...unless the table does not have any regular column, only primary key columns (JAVA-873)
210+ if(!alias.isEmpty()) {
211+ DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
212+ otherColumns.add(ColumnMetadata.forAlias(tm, alias, type));
213+ }
164214 }
165215 }
166216
@@ -170,7 +220,7 @@
170220 case PARTITION_KEY:
171221 partitionKey.set(rawCol.componentIndex, col);
172222 break;
173- case CLUSTERING_KEY:
223+ case CLUSTERING_COLUMN:
174224 clusteringColumns.set(rawCol.componentIndex, col);
175225 clusteringOrder.set(rawCol.componentIndex, rawCol.isReversed ? Order.DESC : Order.ASC);
176226 break;
@@ -187,21 +237,86 @@
187237 for (ColumnMetadata c : otherColumns)
188238 columns.put(c.getName(), c);
189239
190- ksm.add(tm);
191240 return tm;
192241 }
193242
243+ /**
244+ * Upon migration from thrift to CQL, we internally create a pair of surrogate clustering/regular columns
245+ * for compact static tables. These columns shouldn't be exposed to the user but are currently returned by C*.
246+ * We also need to remove the static keyword for all other columns in the table.
247+ */
248+ private static Map<String, ColumnMetadata.Raw> pruneStaticCompactTableColumns(Map<String, ColumnMetadata.Raw> rawCols) {
249+ Collection<ColumnMetadata.Raw> cols = rawCols.values();
250+ Iterator<ColumnMetadata.Raw> it = cols.iterator();
251+ while(it.hasNext()) {
252+ ColumnMetadata.Raw col = it.next();
253+ if(col.kind == ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN) {
254+ // remove "column1 text" clustering column
255+ it.remove();
256+ } else if(col.kind == ColumnMetadata.Raw.Kind.REGULAR) {
257+ // remove "value blob" regular column
258+ it.remove();
259+ } else if(col.kind == ColumnMetadata.Raw.Kind.STATIC) {
260+ // remove "static" keyword
261+ col.kind = ColumnMetadata.Raw.Kind.REGULAR;
262+ }
263+ }
264+ return rawCols;
265+ }
266+
267+ /**
268+ * Upon migration from thrift to CQL, we internally create a surrogate column "value" of type
269+ * EmptyType for dense tables. This column shouldn't be exposed to the user but is currently returned by C*.
270+ */
271+ private static Map<String, ColumnMetadata.Raw> pruneDenseTableColumnsV3(Map<String, ColumnMetadata.Raw> rawCols) {
272+ Collection<ColumnMetadata.Raw> cols = rawCols.values();
273+ Iterator<ColumnMetadata.Raw> it = cols.iterator();
274+ while(it.hasNext()) {
275+ ColumnMetadata.Raw col = it.next();
276+ if(col.kind == ColumnMetadata.Raw.Kind.REGULAR && col.dataType instanceof DataType.CustomType && EMPTY_TYPE.equals(((DataType.CustomType)col.dataType).getCustomTypeClassName())) {
277+ // remove "value EmptyType" regular column
278+ it.remove();
279+ }
280+ }
281+ return rawCols;
282+ }
283+
284+ private static Map<String, ColumnMetadata.Raw> pruneDenseTableColumnsV2(Map<String, ColumnMetadata.Raw> rawCols) {
285+ Collection<ColumnMetadata.Raw> cols = rawCols.values();
286+ Iterator<ColumnMetadata.Raw> it = cols.iterator();
287+ while(it.hasNext()) {
288+ ColumnMetadata.Raw col = it.next();
289+ if(col.kind == ColumnMetadata.Raw.Kind.COMPACT_VALUE && col.name.isEmpty()) {
290+ // remove "" blob regular COMPACT_VALUE column
291+ it.remove();
292+ }
293+ }
294+ return rawCols;
295+ }
296+
297+ private static int findPartitionKeySize(Collection<ColumnMetadata.Raw> cols, CassandraTypeParser.ParseResult keyValidator) {
298+ // C* 1.2, 2.0, 2.1 and 2.2
299+ if(keyValidator != null)
300+ return keyValidator.types.size();
301+ // C* 3.0 onwards
302+ int maxId = -1;
303+ for (ColumnMetadata.Raw col : cols)
304+ if (col.kind == ColumnMetadata.Raw.Kind.PARTITION_KEY)
305+ maxId = Math.max(maxId, col.componentIndex);
306+ return maxId + 1;
307+ }
308+
194309 private static int findClusteringSize(CassandraTypeParser.ParseResult comparator,
195310 Collection<ColumnMetadata.Raw> cols,
196311 List<String> columnAliases,
197312 VersionNumber cassandraVersion) {
198- // In 2.0, this is relatively easy, we just find the biggest 'componentIndex' amongst the clustering columns.
313+ // In 2.0 onwards, this is relatively easy, we just find the biggest 'componentIndex' amongst the clustering columns.
199314 // For 1.2 however, this is slightly more subtle: we need to infer it based on whether the comparator is composite or not, and whether we have
200315 // regular columns or not.
201316 if (cassandraVersion.getMajor() >= 2) {
202317 int maxId = -1;
203318 for (ColumnMetadata.Raw col : cols)
204- if (col.kind == ColumnMetadata.Raw.Kind.CLUSTERING_KEY)
319+ if (col.kind == ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN)
205320 maxId = Math.max(maxId, col.componentIndex);
206321 return maxId + 1;
207322 } else {
@@ -515,16 +630,17 @@
515630
516631 private static final String COMMENT = "comment";
517632 private static final String READ_REPAIR = "read_repair_chance";
633+ private static final String DCLOCAL_READ_REPAIR = "dclocal_read_repair_chance";
518634 private static final String LOCAL_READ_REPAIR = "local_read_repair_chance";
519635 private static final String REPLICATE_ON_WRITE = "replicate_on_write";
520636 private static final String GC_GRACE = "gc_grace_seconds";
521637 private static final String BF_FP_CHANCE = "bloom_filter_fp_chance";
522638 private static final String CACHING = "caching";
639+ private static final String COMPACTION = "compaction";
523640 private static final String COMPACTION_CLASS = "compaction_strategy_class";
524641 private static final String COMPACTION_OPTIONS = "compaction_strategy_options";
525- private static final String MIN_COMPACTION_THRESHOLD = "min_compaction_threshold";
526- private static final String MAX_COMPACTION_THRESHOLD = "max_compaction_threshold";
527642 private static final String POPULATE_CACHE_ON_FLUSH = "populate_io_cache_on_flush";
643+ private static final String COMPRESSION = "compression";
528644 private static final String COMPRESSION_PARAMS = "compression_parameters";
529645 private static final String MEMTABLE_FLUSH_PERIOD_MS = "memtable_flush_period_in_ms";
530646 private static final String DEFAULT_TTL = "default_time_to_live";
@@ -559,32 +675,41 @@
559675 private final Integer indexInterval;
560676 private final Integer minIndexInterval;
561677 private final Integer maxIndexInterval;
562- private final Map<String, String> compaction = new HashMap<String, String>();
563- private final Map<String, String> compression = new HashMap<String, String>();
678+ private final Map<String, String> compaction;
679+ private final Map<String, String> compression;
564680
565681 Options(Row row, boolean isCompactStorage, VersionNumber version) {
682+
683+ boolean is120 = version.getMajor() < 2;
684+ boolean is200 = version.getMajor() == 2 && version.getMinor() == 0;
685+ boolean is210 = version.getMajor() == 2 && version.getMinor() >= 1;
686+ boolean is300OrHigher = version.getMajor() > 2;
687+ boolean is210OrHigher = is210 || is300OrHigher;
688+
566689 this.isCompactStorage = isCompactStorage;
567690 this.comment = isNullOrAbsent(row, COMMENT) ? "" : row.getString(COMMENT);
568691 this.readRepair = row.getDouble(READ_REPAIR);
569- this.localReadRepair = row.getDouble(LOCAL_READ_REPAIR);
570- boolean is210OrMore = version.getMajor() > 2 || (version.getMajor() == 2 && version.getMinor() >= 1);
571- this.replicateOnWrite = is210OrMore || isNullOrAbsent(row, REPLICATE_ON_WRITE) ? DEFAULT_REPLICATE_ON_WRITE : row.getBool(REPLICATE_ON_WRITE);
692+
693+ if(is300OrHigher)
694+ this.localReadRepair = row.getDouble(DCLOCAL_READ_REPAIR);
695+ else
696+ this.localReadRepair = row.getDouble(LOCAL_READ_REPAIR);
697+
698+ this.replicateOnWrite = is210OrHigher || isNullOrAbsent(row, REPLICATE_ON_WRITE) ? DEFAULT_REPLICATE_ON_WRITE : row.getBool(REPLICATE_ON_WRITE);
572699 this.gcGrace = row.getInt(GC_GRACE);
573700 this.bfFpChance = isNullOrAbsent(row, BF_FP_CHANCE) ? DEFAULT_BF_FP_CHANCE : row.getDouble(BF_FP_CHANCE);
574- this.caching = is210OrMore
575- ? SimpleJSONParser.parseStringMap(row.getString(CACHING))
576- : ImmutableMap.of("keys", row.getString(CACHING));
701+
577702 this.populateCacheOnFlush = isNullOrAbsent(row, POPULATE_CACHE_ON_FLUSH) ? DEFAULT_POPULATE_CACHE_ON_FLUSH : row.getBool(POPULATE_CACHE_ON_FLUSH);
578- this.memtableFlushPeriodMs = version.getMajor() < 2 || isNullOrAbsent(row, MEMTABLE_FLUSH_PERIOD_MS) ? DEFAULT_MEMTABLE_FLUSH_PERIOD : row.getInt(MEMTABLE_FLUSH_PERIOD_MS);
579- this.defaultTTL = version.getMajor() < 2 || isNullOrAbsent(row, DEFAULT_TTL) ? DEFAULT_DEFAULT_TTL : row.getInt(DEFAULT_TTL);
580- this.speculativeRetry = version.getMajor() < 2 || isNullOrAbsent(row, SPECULATIVE_RETRY) ? DEFAULT_SPECULATIVE_RETRY : row.getString(SPECULATIVE_RETRY);
581-
582- if (version.getMajor() >= 2 && !is210OrMore)
703+ this.memtableFlushPeriodMs = is120 || isNullOrAbsent(row, MEMTABLE_FLUSH_PERIOD_MS) ? DEFAULT_MEMTABLE_FLUSH_PERIOD : row.getInt(MEMTABLE_FLUSH_PERIOD_MS);
704+ this.defaultTTL = is120 || isNullOrAbsent(row, DEFAULT_TTL) ? DEFAULT_DEFAULT_TTL : row.getInt(DEFAULT_TTL);
705+ this.speculativeRetry = is120 || isNullOrAbsent(row, SPECULATIVE_RETRY) ? DEFAULT_SPECULATIVE_RETRY : row.getString(SPECULATIVE_RETRY);
706+
707+ if (is200)
583708 this.indexInterval = isNullOrAbsent(row, INDEX_INTERVAL) ? DEFAULT_INDEX_INTERVAL : row.getInt(INDEX_INTERVAL);
584709 else
585710 this.indexInterval = null;
586711
587- if (is210OrMore) {
712+ if (is210OrHigher) {
588713 this.minIndexInterval = isNullOrAbsent(row, MIN_INDEX_INTERVAL)
589714 ? DEFAULT_MIN_INDEX_INTERVAL
590715 : row.getInt(MIN_INDEX_INTERVAL);
@@ -596,10 +721,27 @@
596721 this.maxIndexInterval = null;
597722 }
598723
599- this.compaction.put("class", row.getString(COMPACTION_CLASS));
600- this.compaction.putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)));
724+ if (is300OrHigher) {
725+ this.caching = ImmutableMap.copyOf(row.getMap(CACHING, String.class, String.class));
726+ } else if (is210) {
727+ this.caching = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(CACHING)));
728+ } else {
729+ this.caching = ImmutableMap.of("keys", row.getString(CACHING));
730+ }
731+
732+ if (is300OrHigher)
733+ this.compaction = ImmutableMap.copyOf(row.getMap(COMPACTION, String.class, String.class));
734+ else {
735+ this.compaction = ImmutableMap.<String, String>builder()
736+ .put("class", row.getString(COMPACTION_CLASS))
737+ .putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)))
738+ .build();
739+ }
601740
602- this.compression.putAll(SimpleJSONParser.parseStringMap(row.getString(COMPRESSION_PARAMS)));
741+ if(is300OrHigher)
742+ this.compression = ImmutableMap.copyOf(row.getMap(COMPRESSION, String.class, String.class));
743+ else
744+ this.compression = ImmutableMap.copyOf(SimpleJSONParser.parseStringMap(row.getString(COMPRESSION_PARAMS)));
603745 }
604746
605747 private static boolean isNullOrAbsent(Row row, String name) {
@@ -628,7 +770,7 @@
628770 /**
629771 * Returns the chance with which a read repair is triggered for this table.
630772 *
631- * @return the read repair change set for table (in [0.0, 1.0]).
773+ * @return the read repair chance set for table (in [0.0, 1.0]).
632774 */
633775 public double getReadRepairChance() {
634776 return readRepair;
@@ -637,7 +779,7 @@
637779 /**
638780 * Returns the cluster local read repair chance set for this table.
639781 *
640- * @return the local read repair change set for table (in [0.0, 1.0]).
782+ * @return the local read repair chance set for table (in [0.0, 1.0]).
641783 */
642784 public double getLocalReadRepairChance() {
643785 return localReadRepair;
@@ -675,7 +817,7 @@
675817 /**
676818 * Returns the caching options for this table.
677819 *
678- * @return the caching options for this table.
820+ * @return an immutable map containing the caching options for this table.
679821 */
680822 public Map<String, String> getCaching() {
681823 return caching;
@@ -769,19 +911,19 @@
769911 /**
770912 * Returns the compaction options for this table.
771913 *
772- * @return a map containing the compaction options for this table.
914+ * @return an immutable map containing the compaction options for this table.
773915 */
774916 public Map<String, String> getCompaction() {
775- return new HashMap<String, String>(compaction);
917+ return compaction;
776918 }
777919
778920 /**
779921 * Returns the compression options for this table.
780922 *
781- * @return a map containing the compression options for this table.
923+ * @return an immutable map containing the compression options for this table.
782924 */
783925 public Map<String, String> getCompression() {
784- return new HashMap<String, String>(compression);
926+ return compression;
785927 }
786928 }
787929 }
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +1 −1
@@ -27,7 +27,7 @@
2727 */
2828 public class UserType extends DataType implements Iterable<UserType.Field>{
2929
30- private static final String TYPE_NAME = "type_name";
30+ private static final String TYPE_NAME = "type_name";
3131 private static final String COLS_NAMES = "field_names";
3232 private static final String COLS_TYPES = "field_types";
3333
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +5 −4
@@ -15,12 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import org.testng.annotations.Test;
21-import static org.testng.Assert.*;
2219
23-import static com.datastax.driver.core.TestUtils.*;
20+import static org.testng.Assert.assertEquals;
21+import static org.testng.Assert.assertNotNull;
22+import static org.testng.Assert.assertNull;
23+
24+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2425
2526 public class CaseSensitivityTest {
2627
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +1 −0
@@ -73,6 +73,7 @@
7373
7474 // ensure bootstrapping a node does not create additional connections
7575 ccmBridge.bootstrapNode(2);
76+ ccmBridge.waitForUp(2);
7677 assertThat(cluster).host(2).comesUpWithin(2, MINUTES);
7778
7879 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +22 −4
@@ -111,6 +111,23 @@
111111 assertThat(table.getColumns().get(3)).isNotNull().hasName("v").isRegularColumn().hasType(cint());
112112 }
113113
114+ @Test(groups = "short")
115+ public void should_parse_dense_table() {
116+ // given
117+ String cql = String.format("CREATE TABLE %s.dense (\n"
118+ + " k int,\n"
119+ + " c int,\n"
120+ + " PRIMARY KEY (k, c)\n"
121+ + " ) WITH COMPACT STORAGE;", keyspace);
122+ // when
123+ session.execute(cql);
124+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("dense");
125+ // then
126+ assertThat(table).isNotNull().hasName("dense").hasNumberOfColumns(2).isCompactStorage();
127+ assertThat(table.getColumns().get(0)).isNotNull().hasName("k").isPartitionKey().hasType(cint());
128+ assertThat(table.getColumns().get(1)).isNotNull().hasName("c").isClusteringColumn().hasType(cint());
129+ }
130+
114131 @Test(groups = "short")
115132 public void should_parse_compact_dynamic_table() {
116133 // given
@@ -184,6 +201,7 @@
184201 assertThat(table.getColumns().get(3)).isNotNull().hasName("i").isRegularColumn().hasType(cint());
185202 assertThat(table);
186203 VersionNumber version = TestUtils.findHost(cluster, 1).getCassandraVersion();
204+
187205 // Cassandra 3.0 +
188206 if (version.getMajor() > 2) {
189207
@@ -223,7 +241,7 @@
223241 .doesNotContain(" index_interval")
224242 .doesNotContain("replicate_on_write");
225243
226- // Cassandra 2.1 and 2.2
244+ // Cassandra 2.1 and 2.2
227245 } else if (version.getMajor() == 2 && version.getMinor() > 0) {
228246
229247 // With 2.1 we have different options, the caching option changes and replicate_on_write disappears
@@ -263,7 +281,7 @@
263281 .doesNotContain(" index_interval")
264282 .doesNotContain("replicate_on_write");
265283
266- // Cassandra 2.0
284+ // Cassandra 2.0
267285 } else if (version.getMajor() == 2 && version.getMinor() == 0) {
268286
269287 assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5);
@@ -301,7 +319,7 @@
301319 .doesNotContain("min_index_interval") // 2.1 +
302320 .doesNotContain("max_index_interval"); // 2.1 +
303321
304- // Cassandra 1.2
322+ // Cassandra 1.2
305323 } else {
306324
307325 assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5);
@@ -361,6 +379,6 @@
361379 @Override
362380 protected Collection<String> getTableDefinitions() {
363381 return Collections.emptyList();
364-}
382+ }
365383
366384 }