Elffuss BraidHub

kikocis/java-driver public

JAVA-936: Adapt schema metadata parsing logic to new storage format of CQL types in C* 3.0.

This commit also migrates the 'initcond' column type in table
'system_schema.aggregates' from blob to varchar (see CASSANDRA-10650).
Changeset32c367dda3f1dbd28c95749a8d9d41fc83932a94705dc8342a18b3fd7d79d60e
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-09-16 16:00 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-11-13 20:58 +01:00
Parentscd86ebbd4272

Browse the files at this changeset

31 files changed

modified changelog/README.md +2 −1
@@ -5,7 +5,7 @@
55 - [improvement] JAVA-958: Make TableOrView.Order visible.
66 - [improvement] JAVA-968: Update metrics to the latest version.
77 - [improvement] JAVA-965: Improve error handling for when a non-type 1 UUID is given to bind() on a timeuuid column.
8-- [improvement] JAVA-885: Pass the authenticator name from the server to the auth provider.
8+- [improvement] JAVA-885: Pass the authenticator name from the server to the auth provider.
99 - [improvement] JAVA-961: Raise an exception when an older version of guava (<16.01) is found.
1010 - [bug] JAVA-972: TypeCodec.parse() implementations should be case insensitive when checking for keyword NULL.
1111 - [bug] JAVA-971: Make type codecs invariant.
@@ -13,6 +13,7 @@
1313 - [improvement] JAVA-841: Refactor SSLOptions API.
1414 - [improvement] JAVA-948: Don't limit cipher suites by default.
1515 - [improvement] JAVA-917: Document SSL configuration.
16+- [improvement] JAVA-936: Adapt schema metadata parsing logic to new storage format of CQL types in C* 3.0.
1617
1718 Merged from 2.1 branch:
1819
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +52 −19
@@ -58,6 +58,7 @@
5858 this.stateTypeCodec = stateTypeCodec;
5959 }
6060
61+ // Cassandra < 3.0:
6162 // CREATE TABLE system.schema_aggregates (
6263 // keyspace_name text,
6364 // aggregate_name text,
@@ -70,42 +71,74 @@
7071 // state_type text,
7172 // PRIMARY KEY (keyspace_name, aggregate_name, signature)
7273 // ) WITH CLUSTERING ORDER BY (aggregate_name ASC, signature ASC)
73- static AggregateMetadata build(KeyspaceMetadata ksm, Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
74+ //
75+ // Cassandra >= 3.0:
76+ // CREATE TABLE system.schema_aggregates (
77+ // keyspace_name text,
78+ // aggregate_name text,
79+ // argument_types frozen<list<text>>,
80+ // final_func text,
81+ // initcond text,
82+ // return_type text,
83+ // state_func text,
84+ // state_type text,
85+ // PRIMARY KEY (keyspace_name, aggregate_name, argument_types)
86+ // ) WITH CLUSTERING ORDER BY (aggregate_name ASC, argument_types ASC)
87+ static AggregateMetadata build(KeyspaceMetadata ksm, Row row, VersionNumber version, Cluster cluster) {
88+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
89+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
7490 String simpleName = row.getString("aggregate_name");
75- List<String> signature = row.getList("signature", String.class);
76- String fullName = Metadata.fullFunctionName(simpleName, signature);
77- List<DataType> argumentTypes = parseTypes(row.getList("argument_types", String.class), protocolVersion, codecRegistry);
91+ List<DataType> argumentTypes = parseTypes(ksm, row.getList("argument_types", String.class), version, cluster);
92+ String fullName = Metadata.fullFunctionName(simpleName, argumentTypes);
7893 String finalFuncSimpleName = row.getString("final_func");
79- DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
94+ DataType returnType;
95+ if(version.getMajor() >= 3) {
96+ returnType = DataTypeCqlNameParser.parse(row.getString("return_type"), cluster, ksm.getName(), ksm.userTypes, null, false, false);
97+ } else {
98+ returnType = DataTypeClassNameParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
99+ }
80100 String stateFuncSimpleName = row.getString("state_func");
81101 String stateTypeName = row.getString("state_type");
82- DataType stateType = CassandraTypeParser.parseOne(stateTypeName, protocolVersion, codecRegistry);
83- ByteBuffer rawInitCond = row.getBytes("initcond");
84- Object initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).deserialize(rawInitCond, protocolVersion);
102+ DataType stateType;
103+ Object initCond;
104+ if(version.getMajor() >= 3) {
105+ stateType = DataTypeCqlNameParser.parse(stateTypeName, cluster, ksm.getName(), ksm.userTypes, null, false, false);
106+ String rawInitCond = row.getString("initcond");
107+ initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).parse(rawInitCond);
108+ } else {
109+ stateType = DataTypeClassNameParser.parseOne(stateTypeName, protocolVersion, codecRegistry);
110+ ByteBuffer rawInitCond = row.getBytes("initcond");
111+ initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).deserialize(rawInitCond, protocolVersion);
112+ }
85113
86114 String finalFuncFullName = finalFuncSimpleName == null ? null : String.format("%s(%s)", finalFuncSimpleName, stateType);
87- String stateFuncFullName = makeStateFuncFullName(stateFuncSimpleName, stateType.toString(), signature);
115+ String stateFuncFullName = makeStateFuncFullName(stateFuncSimpleName, stateType, argumentTypes);
88116
89- AggregateMetadata aggregate = new AggregateMetadata(ksm, fullName, simpleName, argumentTypes,
117+ return new AggregateMetadata(ksm, fullName, simpleName, argumentTypes,
90118 finalFuncSimpleName, finalFuncFullName, initCond, returnType, stateFuncSimpleName,
91119 stateFuncFullName, stateType, codecRegistry.codecFor(stateType));
92- ksm.add(aggregate);
93- return aggregate;
94120 }
95121
96- private static String makeStateFuncFullName(String stateFuncSimpleName, String stateTypeName, List<String> typeNames) {
97- List<String> args = Lists.newArrayList(stateTypeName);
98- args.addAll(typeNames);
122+ private static String makeStateFuncFullName(String stateFuncSimpleName, DataType stateType, List<DataType> argumentTypes) {
123+ List<DataType> args = Lists.newArrayList(stateType);
124+ args.addAll(argumentTypes);
99125 return Metadata.fullFunctionName(stateFuncSimpleName, args);
100126 }
101127
102- private static List<DataType> parseTypes(List<String> names, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
103- if (names.isEmpty())
128+ private static List<DataType> parseTypes(KeyspaceMetadata ksm, List<String> types, VersionNumber version, Cluster cluster) {
129+ if (types.isEmpty())
104130 return Collections.emptyList();
105131
132+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
133+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
106134 ImmutableList.Builder<DataType> builder = ImmutableList.builder();
107- for (String name : names) {
108- DataType type = CassandraTypeParser.parseOne(name, protocolVersion, codecRegistry);
135+ for (String name : types) {
136+ DataType type;
137+ if (version.getMajor() >= 3) {
138+ type = DataTypeCqlNameParser.parse(name, cluster, ksm.getName(), ksm.userTypes, null, false, false);
139+ } else {
140+ type = DataTypeClassNameParser.parseOne(name, protocolVersion, codecRegistry);
141+ }
109142 builder.add(type);
110143 }
111144 return builder.build();
deleted driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +0 −404
@@ -1,404 +0,0 @@
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.collect.ImmutableMap;
21-import org.slf4j.Logger;
22-import org.slf4j.LoggerFactory;
23-
24-import com.datastax.driver.core.exceptions.DriverInternalError;
25-import com.datastax.driver.core.utils.Bytes;
26-
27-/*
28- * Helps transforming Cassandra types (as read in the schema tables) to
29- * DataType.
30- *
31- * This is modified (and simplified) from Cassandra's TypeParser class to suit
32- * our needs. In particular it's not very efficient, but it doesn't really matter
33- * since it's rarely used and never in a critical path.
34- *
35- * Note that those methods all throw DriverInternalError when there is a parsing
36- * problem because in theory we'll only parse class names coming from Cassandra and
37- * so there shouldn't be anything wrong with them.
38- */
39-class CassandraTypeParser {
40- private static final Logger logger = LoggerFactory.getLogger(CassandraTypeParser.class);
41-
42- private static final String REVERSED_TYPE = "org.apache.cassandra.db.marshal.ReversedType";
43- private static final String FROZEN_TYPE = "org.apache.cassandra.db.marshal.FrozenType";
44- private static final String COMPOSITE_TYPE = "org.apache.cassandra.db.marshal.CompositeType";
45- private static final String COLLECTION_TYPE = "org.apache.cassandra.db.marshal.ColumnToCollectionType";
46- private static final String LIST_TYPE = "org.apache.cassandra.db.marshal.ListType";
47- private static final String SET_TYPE = "org.apache.cassandra.db.marshal.SetType";
48- private static final String MAP_TYPE = "org.apache.cassandra.db.marshal.MapType";
49- private static final String UDT_TYPE = "org.apache.cassandra.db.marshal.UserType";
50- private static final String TUPLE_TYPE = "org.apache.cassandra.db.marshal.TupleType";
51-
52- private static ImmutableMap<String, DataType> cassTypeToDataType =
53- new ImmutableMap.Builder<String, DataType>()
54- .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
55- .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
56- .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
57- .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
58- .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
59- .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
60- .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
61- .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
62- .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
63- .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
64- .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
65- .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
66- .put("org.apache.cassandra.db.marshal.SimpleDateType", DataType.date())
67- .put("org.apache.cassandra.db.marshal.TimeType", DataType.time())
68- .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
69- .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
70- .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
71- .put("org.apache.cassandra.db.marshal.ByteType", DataType.tinyint())
72- .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint())
73- .build();
74-
75- static DataType parseOne(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
76- boolean frozen = false;
77- if (isReversed(className)) {
78- // Just skip the ReversedType part, we don't care
79- className = getNestedClassName(className);
80- } else if (isFrozen(className)) {
81- frozen = true;
82- className = getNestedClassName(className);
83- }
84-
85- Parser parser = new Parser(className, 0);
86- String next = parser.parseNextName();
87-
88- if (next.startsWith(LIST_TYPE))
89- return DataType.list(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
90-
91- if (next.startsWith(SET_TYPE))
92- return DataType.set(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
93-
94- if (next.startsWith(MAP_TYPE)) {
95- List<String> params = parser.getTypeParameters();
96- return DataType.map(parseOne(params.get(0), protocolVersion, codecRegistry), parseOne(params.get(1), protocolVersion, codecRegistry), frozen);
97- }
98-
99- if (frozen)
100- logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, "
101- + "this driver version might be too old for your version of Cassandra");
102-
103- if (isUserType(next)) {
104- ++parser.idx; // skipping '('
105-
106- String keyspace = parser.readOne();
107- parser.skipBlankAndComma();
108- String typeName = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + parser.readOne()), protocolVersion);
109- parser.skipBlankAndComma();
110- Map<String, String> rawFields = parser.getNameAndTypeParameters();
111- List<UserType.Field> fields = new ArrayList<UserType.Field>(rawFields.size());
112- for (Map.Entry<String, String> entry : rawFields.entrySet())
113- fields.add(new UserType.Field(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry)));
114- return new UserType(keyspace, typeName, fields, protocolVersion, codecRegistry);
115- }
116-
117- if (isTupleType(next)) {
118- List<String> rawTypes = parser.getTypeParameters();
119- List<DataType> types = new ArrayList<DataType>(rawTypes.size());
120- for (String rawType : rawTypes) {
121- types.add(parseOne(rawType, protocolVersion, codecRegistry));
122- }
123- return new TupleType(types, protocolVersion, codecRegistry);
124- }
125-
126- DataType type = cassTypeToDataType.get(next);
127- return type == null ? DataType.custom(className) : type;
128- }
129-
130- public static boolean isReversed(String className) {
131- return className.startsWith(REVERSED_TYPE);
132- }
133-
134- public static boolean isFrozen(String className) {
135- return className.startsWith(FROZEN_TYPE);
136- }
137-
138- private static String getNestedClassName(String className) {
139- Parser p = new Parser(className, 0);
140- p.parseNextName();
141- List<String> l = p.getTypeParameters();
142- if (l.size() != 1)
143- throw new IllegalStateException();
144- className = l.get(0);
145- return className;
146- }
147-
148- public static boolean isUserType(String className) {
149- return className.startsWith(UDT_TYPE);
150- }
151-
152- public static boolean isTupleType(String className) {
153- return className.startsWith(TUPLE_TYPE);
154- }
155-
156- private static boolean isComposite(String className) {
157- return className.startsWith(COMPOSITE_TYPE);
158- }
159-
160- private static boolean isCollection(String className) {
161- return className.startsWith(COLLECTION_TYPE);
162- }
163-
164- static ParseResult parseWithComposite(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
165- Parser parser = new Parser(className, 0);
166-
167- String next = parser.parseNextName();
168- if (!isComposite(next))
169- return new ParseResult(parseOne(className, protocolVersion, codecRegistry), isReversed(next));
170-
171- List<String> subClassNames = parser.getTypeParameters();
172- int count = subClassNames.size();
173- String last = subClassNames.get(count - 1);
174- Map<String, DataType> collections = new HashMap<String, DataType>();
175- if (isCollection(last)) {
176- count--;
177- Parser collectionParser = new Parser(last, 0);
178- collectionParser.parseNextName(); // skips columnToCollectionType
179- Map<String, String> params = collectionParser.getCollectionsParameters();
180- for (Map.Entry<String, String> entry : params.entrySet())
181- collections.put(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry));
182- }
183-
184- List<DataType> types = new ArrayList<DataType>(count);
185- List<Boolean> reversed = new ArrayList<Boolean>(count);
186- for (int i = 0; i < count; i++) {
187- types.add(parseOne(subClassNames.get(i), protocolVersion, codecRegistry));
188- reversed.add(isReversed(subClassNames.get(i)));
189- }
190-
191- return new ParseResult(true, types, reversed, collections);
192- }
193-
194- static class ParseResult {
195- public final boolean isComposite;
196- public final List<DataType> types;
197- public final List<Boolean> reversed;
198- public final Map<String, DataType> collections;
199-
200- private ParseResult(DataType type, boolean reversed) {
201- this(false,
202- Collections.<DataType>singletonList(type),
203- Collections.<Boolean>singletonList(reversed),
204- Collections.<String, DataType>emptyMap());
205- }
206-
207- private ParseResult(boolean isComposite, List<DataType> types, List<Boolean> reversed, Map<String, DataType> collections) {
208- this.isComposite = isComposite;
209- this.types = types;
210- this.reversed = reversed;
211- this.collections = collections;
212- }
213- }
214-
215- private static class Parser {
216-
217- private final String str;
218- private int idx;
219-
220- private Parser(String str, int idx) {
221- this.str = str;
222- this.idx = idx;
223- }
224-
225- public String parseNextName() {
226- skipBlank();
227- return readNextIdentifier();
228- }
229-
230- public String readOne() {
231- String name = parseNextName();
232- String args = readRawArguments();
233- return name + args;
234- }
235-
236- // Assumes we have just read a class name and read it's potential arguments
237- // blindly. I.e. it assume that either parsing is done or that we're on a '('
238- // and this reads everything up until the corresponding closing ')'. It
239- // returns everything read, including the enclosing parenthesis.
240- private String readRawArguments() {
241- skipBlank();
242-
243- if (isEOS() || str.charAt(idx) == ')' || str.charAt(idx) == ',')
244- return "";
245-
246- if (str.charAt(idx) != '(')
247- throw new IllegalStateException(String.format("Expecting char %d of %s to be '(' but '%c' found", idx, str, str.charAt(idx)));
248-
249- int i = idx;
250- int open = 1;
251- while (open > 0) {
252- ++idx;
253-
254- if (isEOS())
255- throw new IllegalStateException("Non closed parenthesis");
256-
257- if (str.charAt(idx) == '(') {
258- open++;
259- } else if (str.charAt(idx) == ')') {
260- open--;
261- }
262- }
263- // we've stopped at the last closing ')' so move past that
264- ++idx;
265- return str.substring(i, idx);
266- }
267-
268- public List<String> getTypeParameters() {
269- List<String> list = new ArrayList<String>();
270-
271- if (isEOS())
272- return list;
273-
274- if (str.charAt(idx) != '(')
275- throw new IllegalStateException();
276-
277- ++idx; // skipping '('
278-
279- while (skipBlankAndComma()) {
280- if (str.charAt(idx) == ')') {
281- ++idx;
282- return list;
283- }
284-
285- try {
286- list.add(readOne());
287- } catch (DriverInternalError e) {
288- DriverInternalError ex = new DriverInternalError(String.format("Exception while parsing '%s' around char %d", str, idx));
289- ex.initCause(e);
290- throw ex;
291- }
292- }
293- throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
294- }
295-
296- public Map<String, String> getCollectionsParameters() {
297- if (isEOS())
298- return Collections.<String, String>emptyMap();
299-
300- if (str.charAt(idx) != '(')
301- throw new IllegalStateException();
302-
303- ++idx; // skipping '('
304-
305- return getNameAndTypeParameters();
306- }
307-
308- // Must be at the start of the first parameter to read
309- public Map<String, String> getNameAndTypeParameters() {
310- // The order of the hashmap matters for UDT
311- Map<String, String> map = new LinkedHashMap<String, String>();
312-
313- while (skipBlankAndComma()) {
314- if (str.charAt(idx) == ')') {
315- ++idx;
316- return map;
317- }
318-
319- String bbHex = readNextIdentifier();
320- String name = null;
321- try {
322- name = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED);
323- } catch (NumberFormatException e) {
324- throwSyntaxError(e.getMessage());
325- }
326-
327- skipBlank();
328- if (str.charAt(idx) != ':')
329- throwSyntaxError("expecting ':' token");
330-
331- ++idx;
332- skipBlank();
333- try {
334- map.put(name, readOne());
335- } catch (DriverInternalError e) {
336- DriverInternalError ex = new DriverInternalError(String.format("Exception while parsing '%s' around char %d", str, idx));
337- ex.initCause(e);
338- throw ex;
339- }
340- }
341- throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
342- }
343-
344- private void throwSyntaxError(String msg) {
345- throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: %s", str, idx, msg));
346- }
347-
348- private boolean isEOS() {
349- return isEOS(str, idx);
350- }
351-
352- private static boolean isEOS(String str, int i) {
353- return i >= str.length();
354- }
355-
356- private void skipBlank() {
357- idx = skipBlank(str, idx);
358- }
359-
360- private static int skipBlank(String str, int i) {
361- while (!isEOS(str, i) && ParseUtils.isBlank(str.charAt(i)))
362- ++i;
363-
364- return i;
365- }
366-
367- // skip all blank and at best one comma, return true if there not EOS
368- private boolean skipBlankAndComma() {
369- boolean commaFound = false;
370- while (!isEOS()) {
371- int c = str.charAt(idx);
372- if (c == ',') {
373- if (commaFound)
374- return true;
375- else
376- commaFound = true;
377- } else if (!ParseUtils.isBlank(c)) {
378- return true;
379- }
380- ++idx;
381- }
382- return false;
383- }
384-
385- // left idx positioned on the character stopping the read
386- public String readNextIdentifier() {
387- int i = idx;
388- while (!isEOS() && ParseUtils.isIdentifierChar(str.charAt(idx)))
389- ++idx;
390-
391- return str.substring(i, idx);
392- }
393-
394- public char readNextChar() {
395- skipBlank();
396- return str.charAt(idx++);
397- }
398-
399- @Override
400- public String toString() {
401- return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
402- }
403- }
404-}
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +2 −0
@@ -499,6 +499,8 @@
499499 throw (CodecNotFoundException) e.getCause();
500500 }
501501 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
502+ } catch (RuntimeException e) {
503+ throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
502504 } catch (ExecutionException e) {
503505 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
504506 }
modified driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +1 −1
@@ -80,7 +80,7 @@
8080 if(cqlType instanceof UserType) {
8181 UserType userType = (UserType)cqlType;
8282 userType.setCodecRegistry(codecRegistry);
83- for (UserType.Field field : userType.byIdx) {
83+ for (UserType.Field field : userType.getFields()) {
8484 setCodecRegistry(field.getType(), codecRegistry);
8585 }
8686 }
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +14 −14
@@ -56,8 +56,8 @@
5656 this.isStatic = isStatic;
5757 }
5858
59- static ColumnMetadata fromRaw(TableOrView tm, Raw raw) {
60- return new ColumnMetadata(tm, raw.name, raw.dataType, raw.kind == Raw.Kind.STATIC);
59+ static ColumnMetadata fromRaw(TableOrView tm, Raw raw, DataType dataType) {
60+ return new ColumnMetadata(tm, raw.name, dataType, raw.kind == Raw.Kind.STATIC);
6161 }
6262
6363 static ColumnMetadata forAlias(TableMetadata tm, String name, DataType type) {
@@ -165,12 +165,12 @@
165165 public final String name;
166166 public Kind kind;
167167 public final int position;
168- public final DataType dataType;
168+ public final String dataType;
169169 public final boolean isReversed;
170170
171171 public final Map<String, String> indexColumns = new HashMap<String, String>();
172172
173- Raw(String name, Kind kind, int position, DataType dataType, boolean isReversed) {
173+ Raw(String name, Kind kind, int position, String dataType, boolean isReversed) {
174174 this.name = name;
175175 this.kind = kind;
176176 this.position = position;
@@ -178,7 +178,7 @@
178178 this.isReversed = isReversed;
179179 }
180180
181- static Raw fromRow(Row row, VersionNumber version, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
181+ static Raw fromRow(Row row, VersionNumber version) {
182182 String name = row.getString(COLUMN_NAME);
183183
184184 Kind kind;
@@ -198,26 +198,26 @@
198198 position = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
199199 }
200200
201- String dataTypeStr;
201+ String dataType;
202202 boolean reversed;
203203 if(version.getMajor() >= 3) {
204- dataTypeStr = row.getString(TYPE);
204+ dataType = row.getString(TYPE);
205205 String clusteringOrderStr = row.getString(CLUSTERING_ORDER);
206206 reversed = clusteringOrderStr.equals(DESC);
207207 } else {
208- dataTypeStr = row.getString(VALIDATOR);
209- reversed = CassandraTypeParser.isReversed(dataTypeStr);
208+ dataType = row.getString(VALIDATOR);
209+ reversed = DataTypeClassNameParser.isReversed(dataType);
210210 }
211- DataType dataType = CassandraTypeParser.parseOne(dataTypeStr, protocolVersion, codecRegistry);
212211
213212 Raw c = new Raw(name, kind, position, dataType, reversed);
214213
215214 // secondary indexes (C* < 3.0.0)
216215 // from C* 3.0 onwards 2i are defined in a separate table
217- for (String str : Arrays.asList(INDEX_TYPE, INDEX_NAME, INDEX_OPTIONS))
218- if (row.getColumnDefinitions().contains(str) && !row.isNull(str))
219- c.indexColumns.put(str, row.getString(str));
220-
216+ if(version.getMajor() < 3) {
217+ for (String str : Arrays.asList(INDEX_TYPE, INDEX_NAME, INDEX_OPTIONS))
218+ if (row.getColumnDefinitions().contains(str) && !row.isNull(str))
219+ c.indexColumns.put(str, row.getString(str));
220+ }
221221 return c;
222222 }
223223 }
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +1 −1
@@ -340,7 +340,7 @@
340340 }
341341
342342 SchemaParser.forVersion(cassandraVersion)
343- .refresh(cluster.metadata,
343+ .refresh(cluster.getCluster(),
344344 targetType, targetKeyspace, targetName, targetSignature,
345345 connection, cassandraVersion);
346346 }
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +2 −2
@@ -162,8 +162,8 @@
162162 switch (name) {
163163 case CUSTOM:
164164 String className = CBUtil.readString(buffer);
165- return CassandraTypeParser.isUserType(className) || CassandraTypeParser.isTupleType(className)
166- ? CassandraTypeParser.parseOne(className, protocolVersion, codecRegistry)
165+ return DataTypeClassNameParser.isUserType(className) || DataTypeClassNameParser.isTupleType(className)
166+ ? DataTypeClassNameParser.parseOne(className, protocolVersion, codecRegistry)
167167 : custom(className);
168168 case LIST:
169169 return list(decode(buffer, protocolVersion, codecRegistry));
added driver-core/src/main/java/com/datastax/driver/core/DataTypeClassNameParser.java +405 −0
@@ -0,0 +1,405 @@
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.collect.ImmutableMap;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+
24+import com.datastax.driver.core.exceptions.DriverInternalError;
25+import com.datastax.driver.core.utils.Bytes;
26+
27+/*
28+ * Parse data types from schema tables, for Cassandra 3.0 and above.
29+ * In these versions, data types appear as class names, like "org.apache.cassandra.db.marshal.AsciiType"
30+ * or "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)".
31+ *
32+ * This is modified (and simplified) from Cassandra's TypeParser class to suit
33+ * our needs. In particular it's not very efficient, but it doesn't really matter
34+ * since it's rarely used and never in a critical path.
35+ *
36+ * Note that those methods all throw DriverInternalError when there is a parsing
37+ * problem because in theory we'll only parse class names coming from Cassandra and
38+ * so there shouldn't be anything wrong with them.
39+ */
40+class DataTypeClassNameParser {
41+ private static final Logger logger = LoggerFactory.getLogger(DataTypeClassNameParser.class);
42+
43+ private static final String REVERSED_TYPE = "org.apache.cassandra.db.marshal.ReversedType";
44+ private static final String FROZEN_TYPE = "org.apache.cassandra.db.marshal.FrozenType";
45+ private static final String COMPOSITE_TYPE = "org.apache.cassandra.db.marshal.CompositeType";
46+ private static final String COLLECTION_TYPE = "org.apache.cassandra.db.marshal.ColumnToCollectionType";
47+ private static final String LIST_TYPE = "org.apache.cassandra.db.marshal.ListType";
48+ private static final String SET_TYPE = "org.apache.cassandra.db.marshal.SetType";
49+ private static final String MAP_TYPE = "org.apache.cassandra.db.marshal.MapType";
50+ private static final String UDT_TYPE = "org.apache.cassandra.db.marshal.UserType";
51+ private static final String TUPLE_TYPE = "org.apache.cassandra.db.marshal.TupleType";
52+
53+ private static ImmutableMap<String, DataType> cassTypeToDataType =
54+ new ImmutableMap.Builder<String, DataType>()
55+ .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
56+ .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
57+ .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
58+ .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
59+ .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
60+ .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
61+ .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
62+ .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
63+ .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
64+ .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
65+ .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
66+ .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
67+ .put("org.apache.cassandra.db.marshal.SimpleDateType", DataType.date())
68+ .put("org.apache.cassandra.db.marshal.TimeType", DataType.time())
69+ .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
70+ .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
71+ .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
72+ .put("org.apache.cassandra.db.marshal.ByteType", DataType.tinyint())
73+ .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint())
74+ .build();
75+
76+ static DataType parseOne(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
77+ boolean frozen = false;
78+ if (isReversed(className)) {
79+ // Just skip the ReversedType part, we don't care
80+ className = getNestedClassName(className);
81+ } else if (isFrozen(className)) {
82+ frozen = true;
83+ className = getNestedClassName(className);
84+ }
85+
86+ Parser parser = new Parser(className, 0);
87+ String next = parser.parseNextName();
88+
89+ if (next.startsWith(LIST_TYPE))
90+ return DataType.list(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
91+
92+ if (next.startsWith(SET_TYPE))
93+ return DataType.set(parseOne(parser.getTypeParameters().get(0), protocolVersion, codecRegistry), frozen);
94+
95+ if (next.startsWith(MAP_TYPE)) {
96+ List<String> params = parser.getTypeParameters();
97+ return DataType.map(parseOne(params.get(0), protocolVersion, codecRegistry), parseOne(params.get(1), protocolVersion, codecRegistry), frozen);
98+ }
99+
100+ if (frozen)
101+ logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, "
102+ + "this driver version might be too old for your version of Cassandra");
103+
104+ if (isUserType(next)) {
105+ ++parser.idx; // skipping '('
106+
107+ String keyspace = parser.readOne();
108+ parser.skipBlankAndComma();
109+ String typeName = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + parser.readOne()), protocolVersion);
110+ parser.skipBlankAndComma();
111+ Map<String, String> rawFields = parser.getNameAndTypeParameters();
112+ List<UserType.Field> fields = new ArrayList<UserType.Field>(rawFields.size());
113+ for (Map.Entry<String, String> entry : rawFields.entrySet())
114+ fields.add(new UserType.Field(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry)));
115+ return new UserType(keyspace, typeName, fields, protocolVersion, codecRegistry);
116+ }
117+
118+ if (isTupleType(next)) {
119+ List<String> rawTypes = parser.getTypeParameters();
120+ List<DataType> types = new ArrayList<DataType>(rawTypes.size());
121+ for (String rawType : rawTypes) {
122+ types.add(parseOne(rawType, protocolVersion, codecRegistry));
123+ }
124+ return new TupleType(types, protocolVersion, codecRegistry);
125+ }
126+
127+ DataType type = cassTypeToDataType.get(next);
128+ return type == null ? DataType.custom(className) : type;
129+ }
130+
131+ public static boolean isReversed(String className) {
132+ return className.startsWith(REVERSED_TYPE);
133+ }
134+
135+ public static boolean isFrozen(String className) {
136+ return className.startsWith(FROZEN_TYPE);
137+ }
138+
139+ private static String getNestedClassName(String className) {
140+ Parser p = new Parser(className, 0);
141+ p.parseNextName();
142+ List<String> l = p.getTypeParameters();
143+ if (l.size() != 1)
144+ throw new IllegalStateException();
145+ className = l.get(0);
146+ return className;
147+ }
148+
149+ public static boolean isUserType(String className) {
150+ return className.startsWith(UDT_TYPE);
151+ }
152+
153+ public static boolean isTupleType(String className) {
154+ return className.startsWith(TUPLE_TYPE);
155+ }
156+
157+ private static boolean isComposite(String className) {
158+ return className.startsWith(COMPOSITE_TYPE);
159+ }
160+
161+ private static boolean isCollection(String className) {
162+ return className.startsWith(COLLECTION_TYPE);
163+ }
164+
165+ static ParseResult parseWithComposite(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
166+ Parser parser = new Parser(className, 0);
167+
168+ String next = parser.parseNextName();
169+ if (!isComposite(next))
170+ return new ParseResult(parseOne(className, protocolVersion, codecRegistry), isReversed(next));
171+
172+ List<String> subClassNames = parser.getTypeParameters();
173+ int count = subClassNames.size();
174+ String last = subClassNames.get(count - 1);
175+ Map<String, DataType> collections = new HashMap<String, DataType>();
176+ if (isCollection(last)) {
177+ count--;
178+ Parser collectionParser = new Parser(last, 0);
179+ collectionParser.parseNextName(); // skips columnToCollectionType
180+ Map<String, String> params = collectionParser.getCollectionsParameters();
181+ for (Map.Entry<String, String> entry : params.entrySet())
182+ collections.put(entry.getKey(), parseOne(entry.getValue(), protocolVersion, codecRegistry));
183+ }
184+
185+ List<DataType> types = new ArrayList<DataType>(count);
186+ List<Boolean> reversed = new ArrayList<Boolean>(count);
187+ for (int i = 0; i < count; i++) {
188+ types.add(parseOne(subClassNames.get(i), protocolVersion, codecRegistry));
189+ reversed.add(isReversed(subClassNames.get(i)));
190+ }
191+
192+ return new ParseResult(true, types, reversed, collections);
193+ }
194+
195+ static class ParseResult {
196+ public final boolean isComposite;
197+ public final List<DataType> types;
198+ public final List<Boolean> reversed;
199+ public final Map<String, DataType> collections;
200+
201+ private ParseResult(DataType type, boolean reversed) {
202+ this(false,
203+ Collections.<DataType>singletonList(type),
204+ Collections.<Boolean>singletonList(reversed),
205+ Collections.<String, DataType>emptyMap());
206+ }
207+
208+ private ParseResult(boolean isComposite, List<DataType> types, List<Boolean> reversed, Map<String, DataType> collections) {
209+ this.isComposite = isComposite;
210+ this.types = types;
211+ this.reversed = reversed;
212+ this.collections = collections;
213+ }
214+ }
215+
216+ private static class Parser {
217+
218+ private final String str;
219+ private int idx;
220+
221+ private Parser(String str, int idx) {
222+ this.str = str;
223+ this.idx = idx;
224+ }
225+
226+ public String parseNextName() {
227+ skipBlank();
228+ return readNextIdentifier();
229+ }
230+
231+ public String readOne() {
232+ String name = parseNextName();
233+ String args = readRawArguments();
234+ return name + args;
235+ }
236+
237+ // Assumes we have just read a class name and read it's potential arguments
238+ // blindly. I.e. it assume that either parsing is done or that we're on a '('
239+ // and this reads everything up until the corresponding closing ')'. It
240+ // returns everything read, including the enclosing parenthesis.
241+ private String readRawArguments() {
242+ skipBlank();
243+
244+ if (isEOS() || str.charAt(idx) == ')' || str.charAt(idx) == ',')
245+ return "";
246+
247+ if (str.charAt(idx) != '(')
248+ throw new IllegalStateException(String.format("Expecting char %d of %s to be '(' but '%c' found", idx, str, str.charAt(idx)));
249+
250+ int i = idx;
251+ int open = 1;
252+ while (open > 0) {
253+ ++idx;
254+
255+ if (isEOS())
256+ throw new IllegalStateException("Non closed parenthesis");
257+
258+ if (str.charAt(idx) == '(') {
259+ open++;
260+ } else if (str.charAt(idx) == ')') {
261+ open--;
262+ }
263+ }
264+ // we've stopped at the last closing ')' so move past that
265+ ++idx;
266+ return str.substring(i, idx);
267+ }
268+
269+ public List<String> getTypeParameters() {
270+ List<String> list = new ArrayList<String>();
271+
272+ if (isEOS())
273+ return list;
274+
275+ if (str.charAt(idx) != '(')
276+ throw new IllegalStateException();
277+
278+ ++idx; // skipping '('
279+
280+ while (skipBlankAndComma()) {
281+ if (str.charAt(idx) == ')') {
282+ ++idx;
283+ return list;
284+ }
285+
286+ try {
287+ list.add(readOne());
288+ } catch (DriverInternalError e) {
289+ DriverInternalError ex = new DriverInternalError(String.format("Exception while parsing '%s' around char %d", str, idx));
290+ ex.initCause(e);
291+ throw ex;
292+ }
293+ }
294+ throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
295+ }
296+
297+ public Map<String, String> getCollectionsParameters() {
298+ if (isEOS())
299+ return Collections.<String, String>emptyMap();
300+
301+ if (str.charAt(idx) != '(')
302+ throw new IllegalStateException();
303+
304+ ++idx; // skipping '('
305+
306+ return getNameAndTypeParameters();
307+ }
308+
309+ // Must be at the start of the first parameter to read
310+ public Map<String, String> getNameAndTypeParameters() {
311+ // The order of the hashmap matters for UDT
312+ Map<String, String> map = new LinkedHashMap<String, String>();
313+
314+ while (skipBlankAndComma()) {
315+ if (str.charAt(idx) == ')') {
316+ ++idx;
317+ return map;
318+ }
319+
320+ String bbHex = readNextIdentifier();
321+ String name = null;
322+ try {
323+ name = TypeCodec.varchar().deserialize(Bytes.fromHexString("0x" + bbHex), ProtocolVersion.NEWEST_SUPPORTED);
324+ } catch (NumberFormatException e) {
325+ throwSyntaxError(e.getMessage());
326+ }
327+
328+ skipBlank();
329+ if (str.charAt(idx) != ':')
330+ throwSyntaxError("expecting ':' token");
331+
332+ ++idx;
333+ skipBlank();
334+ try {
335+ map.put(name, readOne());
336+ } catch (DriverInternalError e) {
337+ DriverInternalError ex = new DriverInternalError(String.format("Exception while parsing '%s' around char %d", str, idx));
338+ ex.initCause(e);
339+ throw ex;
340+ }
341+ }
342+ throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
343+ }
344+
345+ private void throwSyntaxError(String msg) {
346+ throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: %s", str, idx, msg));
347+ }
348+
349+ private boolean isEOS() {
350+ return isEOS(str, idx);
351+ }
352+
353+ private static boolean isEOS(String str, int i) {
354+ return i >= str.length();
355+ }
356+
357+ private void skipBlank() {
358+ idx = skipBlank(str, idx);
359+ }
360+
361+ private static int skipBlank(String str, int i) {
362+ while (!isEOS(str, i) && ParseUtils.isBlank(str.charAt(i)))
363+ ++i;
364+
365+ return i;
366+ }
367+
368+ // skip all blank and at best one comma, return true if there not EOS
369+ private boolean skipBlankAndComma() {
370+ boolean commaFound = false;
371+ while (!isEOS()) {
372+ int c = str.charAt(idx);
373+ if (c == ',') {
374+ if (commaFound)
375+ return true;
376+ else
377+ commaFound = true;
378+ } else if (!ParseUtils.isBlank(c)) {
379+ return true;
380+ }
381+ ++idx;
382+ }
383+ return false;
384+ }
385+
386+ // left idx positioned on the character stopping the read
387+ public String readNextIdentifier() {
388+ int i = idx;
389+ while (!isEOS() && ParseUtils.isIdentifierChar(str.charAt(idx)))
390+ ++idx;
391+
392+ return str.substring(i, idx);
393+ }
394+
395+ public char readNextChar() {
396+ skipBlank();
397+ return str.charAt(idx++);
398+ }
399+
400+ @Override
401+ public String toString() {
402+ return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
403+ }
404+ }
405+}
added driver-core/src/main/java/com/datastax/driver/core/DataTypeCqlNameParser.java +295 −0
@@ -0,0 +1,295 @@
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.ArrayList;
19+import java.util.List;
20+import java.util.Map;
21+
22+import com.google.common.collect.ImmutableMap;
23+
24+import com.datastax.driver.core.exceptions.DriverInternalError;
25+import com.datastax.driver.core.exceptions.UnresolvedUserTypeException;
26+
27+import static com.datastax.driver.core.DataType.*;
28+import static com.datastax.driver.core.ParseUtils.isBlank;
29+import static com.datastax.driver.core.ParseUtils.isIdentifierChar;
30+import static com.datastax.driver.core.ParseUtils.skipSpaces;
31+
32+/*
33+ * Parse data types from schema tables, for Cassandra 3.0 and above.
34+ * In these versions, data types appear as string literals, like "ascii" or "tuple<int,int>".
35+ *
36+ * Note that these methods all throw DriverInternalError when there is a parsing
37+ * problem because in theory we'll only parse class names coming from Cassandra and
38+ * so there shouldn't be anything wrong with them.
39+ */
40+class DataTypeCqlNameParser {
41+
42+ private static final String FROZEN = "frozen";
43+ private static final String LIST = "list";
44+ private static final String SET = "set";
45+ private static final String MAP = "map";
46+ private static final String TUPLE = "tuple";
47+ private static final String EMPTY = "empty";
48+
49+ private static final ImmutableMap<String, DataType> NATIVE_TYPES_MAP =
50+ new ImmutableMap.Builder<String, DataType>()
51+ .put("ascii", ascii())
52+ .put("bigint", bigint())
53+ .put("blob", blob())
54+ .put("boolean", cboolean())
55+ .put("counter", counter())
56+ .put("decimal", decimal())
57+ .put("double", cdouble())
58+ .put("float", cfloat())
59+ .put("inet", inet())
60+ .put("int", cint())
61+ .put("text", text())
62+ .put("varchar", varchar())
63+ .put("timestamp", timestamp())
64+ .put("date", date())
65+ .put("time", time())
66+ .put("uuid", uuid())
67+ .put("varint", varint())
68+ .put("timeuuid", timeuuid())
69+ .put("tinyint", tinyint())
70+ .put("smallint", smallint())
71+ .build();
72+
73+ /**
74+ * @param currentUserTypes if this method gets called as part of a refresh that spans multiple user types, this contains the ones
75+ * that have already been refreshed. If the type we are parsing references a user type, we want to pick its
76+ * definition from this map in priority.
77+ * @param oldUserTypes this contains all the keyspace's user types as they were before the refresh started. If we can't find a
78+ * definition in {@code currentUserTypes}, we'll check this map as a fallback.
79+ */
80+ static DataType parse(String toParse, Cluster cluster, String currentKeyspaceName, Map<String, UserType> currentUserTypes, Map<String, UserType> oldUserTypes, boolean frozen, boolean shallowUserTypes) {
81+
82+ Parser parser = new Parser(toParse, 0);
83+ String type = parser.parseTypeName();
84+
85+ DataType nativeType = NATIVE_TYPES_MAP.get(type.toLowerCase());
86+ if (nativeType != null)
87+ return nativeType;
88+
89+ if (type.equalsIgnoreCase(LIST)) {
90+ List<String> parameters = parser.parseTypeParameters();
91+ if (parameters.size() != 1)
92+ throw new DriverInternalError(String.format("Excepting single parameter for list, got %s", parameters));
93+ DataType elementType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
94+ return list(elementType, frozen);
95+ }
96+
97+ if (type.equalsIgnoreCase(SET)) {
98+ List<String> parameters = parser.parseTypeParameters();
99+ if (parameters.size() != 1)
100+ throw new DriverInternalError(String.format("Excepting single parameter for set, got %s", parameters));
101+ DataType elementType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
102+ return set(elementType, frozen);
103+ }
104+
105+ if (type.equalsIgnoreCase(MAP)) {
106+ List<String> parameters = parser.parseTypeParameters();
107+ if (parameters.size() != 2)
108+ throw new DriverInternalError(String.format("Excepting two parameters for map, got %s", parameters));
109+ DataType keyType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
110+ DataType valueType = parse(parameters.get(1), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
111+ return map(keyType, valueType, frozen);
112+ }
113+
114+ if (type.equalsIgnoreCase(FROZEN)) {
115+ List<String> parameters = parser.parseTypeParameters();
116+ if (parameters.size() != 1)
117+ throw new DriverInternalError(String.format("Excepting single parameter for frozen keyword, got %s", parameters));
118+ return parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, true, shallowUserTypes);
119+ }
120+
121+ if (type.equalsIgnoreCase(TUPLE)) {
122+ List<String> rawTypes = parser.parseTypeParameters();
123+ List<DataType> types = new ArrayList<DataType>(rawTypes.size());
124+ for (String rawType : rawTypes) {
125+ types.add(parse(rawType, cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes));
126+ }
127+ return cluster.getMetadata().newTupleType(types);
128+ }
129+
130+ // return a custom type for the special empty type
131+ // so that it gets detected later on, see TableMetadata
132+ if(type.equalsIgnoreCase(EMPTY))
133+ return custom(type);
134+
135+ // We need to remove escaped double quotes within the type name as it is stored unescaped.
136+ // Otherwise it's a UDT. If we only want a shallow definition build it, otherwise search known definitions.
137+ if (shallowUserTypes)
138+ return new UserType.Shallow(currentKeyspaceName, Metadata.handleId(type));
139+
140+ UserType userType = null;
141+ if (currentUserTypes != null)
142+ userType = currentUserTypes.get(Metadata.handleId(type));
143+ if (userType == null && oldUserTypes != null)
144+ userType = oldUserTypes.get(Metadata.handleId(type));
145+
146+ if (userType == null)
147+ throw new UnresolvedUserTypeException(currentKeyspaceName, type);
148+ else
149+ return userType;
150+ }
151+
152+ private static class Parser {
153+
154+ private final String str;
155+
156+ private int idx;
157+
158+ Parser(String str, int idx) {
159+ this.str = str;
160+ this.idx = idx;
161+ }
162+
163+ String parseTypeName() {
164+ idx = skipSpaces(str, idx);
165+ return readNextIdentifier();
166+ }
167+
168+ List<String> parseTypeParameters() {
169+ List<String> list = new ArrayList<String>();
170+
171+ if (isEOS())
172+ return list;
173+
174+ skipBlankAndComma();
175+
176+ if (str.charAt(idx) != '<')
177+ throw new IllegalStateException();
178+
179+ ++idx; // skipping '<'
180+
181+ while (skipBlankAndComma()) {
182+ if (str.charAt(idx) == '>') {
183+ ++idx;
184+ return list;
185+ }
186+
187+ try {
188+ String name = parseTypeName();
189+ String args = readRawTypeParameters();
190+ list.add(name + args);
191+ } catch (DriverInternalError e) {
192+ DriverInternalError ex = new DriverInternalError(String.format("Exception while parsing '%s' around char %d", str, idx));
193+ ex.initCause(e);
194+ throw ex;
195+ }
196+ }
197+ throw new DriverInternalError(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
198+ }
199+
200+ // left idx positioned on the character stopping the read
201+ private String readNextIdentifier() {
202+ int startIdx = idx;
203+ // if first character is a quote, this is a quoted identifier.
204+ if(str.charAt(startIdx) == '"') {
205+ ++idx;
206+ // read until closing quote.
207+ while(!isEOS()) {
208+ boolean atQuote = str.charAt(idx) == '"';
209+ ++idx;
210+ if (atQuote) {
211+ // if the next character is also a quote, this is an escaped
212+ // quote, continue reading, otherwise stop.
213+ if(!isEOS() && str.charAt(idx) == '"')
214+ ++idx;
215+ else
216+ break;
217+ }
218+ }
219+ } else {
220+ while (!isEOS() && (isIdentifierChar(str.charAt(idx)) || str.charAt(idx) == '"'))
221+ ++idx;
222+ }
223+ return str.substring(startIdx, idx);
224+ }
225+
226+ // Assumes we have just read a type name and read it's potential arguments
227+ // blindly. I.e. it assume that either parsing is done or that we're on a '<'
228+ // and this reads everything up until the corresponding closing '>'. It
229+ // returns everything read, including the enclosing brackets.
230+ private String readRawTypeParameters() {
231+ idx = skipSpaces(str, idx);
232+
233+ if (isEOS() || str.charAt(idx) == '>' || str.charAt(idx) == ',')
234+ return "";
235+
236+ if (str.charAt(idx) != '<')
237+ throw new IllegalStateException(String.format("Expecting char %d of %s to be '<' but '%c' found", idx, str, str.charAt(idx)));
238+
239+ int i = idx;
240+ int open = 1;
241+ boolean inQuotes = false;
242+ while (open > 0) {
243+ ++idx;
244+
245+ if (isEOS())
246+ throw new IllegalStateException("Non closed angle brackets");
247+
248+ // Only parse for '<' and '>' characters if not within a quoted identifier.
249+ // Note we don't need to handle escaped quotes ("") in type names here, because they just cause inQuotes to flip
250+ // to false and immediately back to true
251+ if(!inQuotes) {
252+ if (str.charAt(idx) == '"') {
253+ inQuotes = true;
254+ } else if (str.charAt(idx) == '<') {
255+ open++;
256+ } else if (str.charAt(idx) == '>') {
257+ open--;
258+ }
259+ } else if(str.charAt(idx) == '"') {
260+ inQuotes = false;
261+ }
262+ }
263+ // we've stopped at the last closing ')' so move past that
264+ ++idx;
265+ return str.substring(i, idx);
266+ }
267+
268+ // skip all blank and at best one comma, return true if there not EOS
269+ private boolean skipBlankAndComma() {
270+ boolean commaFound = false;
271+ while (!isEOS()) {
272+ int c = str.charAt(idx);
273+ if (c == ',') {
274+ if (commaFound)
275+ return true;
276+ else
277+ commaFound = true;
278+ } else if (!isBlank(c)) {
279+ return true;
280+ }
281+ ++idx;
282+ }
283+ return false;
284+ }
285+
286+ private boolean isEOS() {
287+ return idx >= str.length();
288+ }
289+
290+ @Override
291+ public String toString() {
292+ return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
293+ }
294+ }
295+}
added driver-core/src/main/java/com/datastax/driver/core/DirectedGraph.java +92 −0
@@ -0,0 +1,92 @@
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.Preconditions;
21+import com.google.common.collect.HashMultimap;
22+import com.google.common.collect.Lists;
23+import com.google.common.collect.Maps;
24+import com.google.common.collect.Multimap;
25+
26+import com.datastax.driver.core.exceptions.DriverInternalError;
27+
28+/**
29+ * A basic directed graph implementation to perform topological sorts.
30+ */
31+class DirectedGraph<V> {
32+
33+ // We need to keep track of the predecessor count. For simplicity, use a map to store it alongside the vertices.
34+ final Map<V, Integer> vertices;
35+ final Multimap<V, V> adjacencyList;
36+ boolean wasSorted;
37+
38+ DirectedGraph(List<V> vertices) {
39+ this.vertices = Maps.newHashMapWithExpectedSize(vertices.size());
40+ this.adjacencyList = HashMultimap.create();
41+
42+ for (V vertex : vertices) {
43+ this.vertices.put(vertex, 0);
44+ }
45+ }
46+
47+ DirectedGraph(V... vertices) {
48+ this(Arrays.asList(vertices));
49+ }
50+
51+ /** this assumes that {@code from} and {@code to} were part of the vertices passed to the constructor */
52+ void addEdge(V from, V to) {
53+ Preconditions.checkArgument(vertices.containsKey(from) && vertices.containsKey(to));
54+ adjacencyList.put(from, to);
55+ vertices.put(to, vertices.get(to) + 1);
56+ }
57+
58+ /** one-time use only, calling this multiple times on the same graph won't work */
59+ List<V> topologicalSort() {
60+ Preconditions.checkState(!wasSorted);
61+ wasSorted = true;
62+
63+ Queue<V> queue = new LinkedList<V>();
64+
65+ for (Map.Entry<V, Integer> entry : vertices.entrySet()) {
66+ if (entry.getValue() == 0)
67+ queue.add(entry.getKey());
68+ }
69+
70+ List<V> result = Lists.newArrayList();
71+ while (!queue.isEmpty()) {
72+ V vertex = queue.remove();
73+ result.add(vertex);
74+ for (V successor : adjacencyList.get(vertex)) {
75+ if (decrementAndGetCount(successor) == 0)
76+ queue.add(successor);
77+ }
78+ }
79+
80+ if (result.size() != vertices.size())
81+ throw new DriverInternalError("failed to perform topological sort, graph has a cycle");
82+
83+ return result;
84+ }
85+
86+ private int decrementAndGetCount(V vertex) {
87+ Integer count = vertices.get(vertex);
88+ count = count - 1;
89+ vertices.put(vertex, count);
90+ return count;
91+ }
92+}
modified driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java +39 −14
@@ -58,6 +58,7 @@
5858 this.returnType = returnType;
5959 }
6060
61+ // Cassandra < 3.0:
6162 // CREATE TABLE system.schema_functions (
6263 // keyspace_name text,
6364 // function_name text,
@@ -70,41 +71,65 @@
7071 // return_type text,
7172 // PRIMARY KEY (keyspace_name, function_name, signature)
7273 // ) WITH CLUSTERING ORDER BY (function_name ASC, signature ASC)
73- static FunctionMetadata build(KeyspaceMetadata ksm, Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
74- String simpleName = row.getString("function_name");
75- List<String> signature = row.getList("signature", String.class);
76- String fullName = Metadata.fullFunctionName(simpleName, signature);
74+ //
75+ // Cassandra >= 3.0:
76+ // CREATE TABLE system_schema.functions (
77+ // keyspace_name text,
78+ // function_name text,
79+ // argument_names frozen<list<text>>,
80+ // argument_types frozen<list<text>>,
81+ // body text,
82+ // called_on_null_input boolean,
83+ // language text,
84+ // return_type text,
85+ // PRIMARY KEY (keyspace_name, function_name, argument_types)
86+ // ) WITH CLUSTERING ORDER BY (function_name ASC, argument_types ASC)
87+ //
7788
89+ static FunctionMetadata build(KeyspaceMetadata ksm, Row row, VersionNumber version, Cluster cluster) {
90+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
91+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
92+ String simpleName = row.getString("function_name");
7893 List<String> argumentNames = row.getList("argument_names", String.class);
94+ // this will be a list of C* types in 2.2 and a list of CQL types in 3.0
7995 List<String> argumentTypes = row.getList("argument_types", String.class);
96+ Map<String, DataType> arguments = buildArguments(ksm, argumentNames, argumentTypes, version, cluster);
97+ String fullName = Metadata.fullFunctionName(simpleName, arguments.values());
8098 if (argumentNames.size() != argumentTypes.size()) {
8199 logger.error(String.format("Error parsing definition of function %1$s.%2$s: the number of argument names and types don't match."
82100 + "Cluster.getMetadata().getKeyspace(\"%1$s\").getFunction(\"%2$s\") will be missing.",
83101 ksm.getName(), fullName));
84102 return null;
85103 }
86- Map<String, DataType> arguments = buildArguments(argumentNames, argumentTypes, protocolVersion, codecRegistry);
87-
88104 String body = row.getString("body");
89105 boolean calledOnNullInput = row.getBool("called_on_null_input");
90106 String language = row.getString("language");
91- DataType returnType = CassandraTypeParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
92-
93- FunctionMetadata function = new FunctionMetadata(ksm, fullName, simpleName, arguments, body,
107+ DataType returnType;
108+ if(version.getMajor() >= 3.0) {
109+ returnType = DataTypeCqlNameParser.parse(row.getString("return_type"), cluster, ksm.getName(), ksm.userTypes, null, false, false);
110+ } else {
111+ returnType = DataTypeClassNameParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
112+ }
113+ return new FunctionMetadata(ksm, fullName, simpleName, arguments, body,
94114 calledOnNullInput, language, returnType);
95- ksm.add(function);
96- return function;
97115 }
98116
99117 // Note: the caller ensures that names and types have the same size
100- private static Map<String, DataType> buildArguments(List<String> names, List<String> types, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
118+ private static Map<String, DataType> buildArguments(KeyspaceMetadata ksm, List<String> names, List<String> types, VersionNumber version, Cluster cluster) {
101119 if (names.isEmpty())
102120 return Collections.emptyMap();
103-
104121 ImmutableMap.Builder<String, DataType> builder = ImmutableMap.builder();
122+ Metadata metadata = cluster.getMetadata();
123+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
124+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
105125 Iterator<String> iterTypes = types.iterator();
106126 for (String name : names) {
107- DataType type = CassandraTypeParser.parseOne(iterTypes.next(), protocolVersion, codecRegistry);
127+ DataType type;
128+ if (version.getMajor() >= 3) {
129+ type = DataTypeCqlNameParser.parse(iterTypes.next(), cluster, ksm.getName(), ksm.userTypes, null, false, false);
130+ } else {
131+ type = DataTypeClassNameParser.parseOne(iterTypes.next(), protocolVersion, codecRegistry);
132+ }
108133 builder.put(name, type);
109134 }
110135 return builder.build();
modified driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java +10 −2
@@ -56,7 +56,7 @@
5656 this.whereClause = whereClause;
5757 }
5858
59- static MaterializedViewMetadata build(KeyspaceMetadata keyspace, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion) {
59+ static MaterializedViewMetadata build(KeyspaceMetadata keyspace, Row row, Map<String, ColumnMetadata.Raw> rawCols, VersionNumber cassandraVersion, Cluster cluster) {
6060
6161 String name = row.getString("view_name");
6262 String tableName = row.getString("base_table_name");
@@ -101,7 +101,15 @@
101101 // 'SELECT * FROM ...'
102102 Set<ColumnMetadata> otherColumns = new TreeSet<ColumnMetadata>(columnMetadataComparator);
103103 for (ColumnMetadata.Raw rawCol : rawCols.values()) {
104- ColumnMetadata col = ColumnMetadata.fromRaw(view, rawCol);
104+ DataType dataType;
105+ if(cassandraVersion.getMajor() >= 3) {
106+ dataType = DataTypeCqlNameParser.parse(rawCol.dataType, cluster, keyspace.getName(), keyspace.userTypes, keyspace.userTypes, false, false);
107+ } else {
108+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
109+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
110+ dataType = DataTypeClassNameParser.parseOne(rawCol.dataType, protocolVersion, codecRegistry);
111+ }
112+ ColumnMetadata col = ColumnMetadata.fromRaw(view, rawCol, dataType);
105113 switch (rawCol.kind) {
106114 case PARTITION_KEY:
107115 partitionKey.set(rawCol.position, col);
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +11 −1
@@ -364,7 +364,17 @@
364364 * @return the newly created tuple type.
365365 */
366366 public TupleType newTupleType(DataType... types) {
367- return new TupleType(Arrays.asList(types), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
367+ return newTupleType(Arrays.asList(types));
368+ }
369+
370+ /**
371+ * Creates a tuple type given a list of types.
372+ *
373+ * @param types the types for the tuple type.
374+ * @return the newly created tuple type.
375+ */
376+ public TupleType newTupleType(List<DataType> types) {
377+ return new TupleType(types, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
368378 }
369379
370380 /**
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +101 −55
@@ -26,7 +26,7 @@
2626 import static com.datastax.driver.core.SchemaElement.*;
2727
2828 abstract class SchemaParser {
29-
29+
3030 private static final Logger logger = LoggerFactory.getLogger(SchemaParser.class);
3131
3232 private static final TypeCodec<List<String>> LIST_OF_TEXT_CODEC = TypeCodec.list(TypeCodec.varchar());
@@ -39,26 +39,27 @@
3939 return V2_PARSER;
4040 }
4141
42- abstract SystemRows fetchSystemRows(Metadata metadata,
42+ abstract SystemRows fetchSystemRows(Cluster cluster,
4343 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
4444 Connection connection, VersionNumber cassandraVersion)
4545 throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException;
4646
4747 abstract String tableNameColumn();
4848
49- void refresh(Metadata metadata,
49+ void refresh(Cluster cluster,
5050 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
5151 Connection connection, VersionNumber cassandraVersion)
5252 throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
5353
54- SystemRows rows = fetchSystemRows(metadata, targetType, targetKeyspace, targetName, targetSignature, connection, cassandraVersion);
54+ SystemRows rows = fetchSystemRows(cluster, targetType, targetKeyspace, targetName, targetSignature, connection, cassandraVersion);
5555
56+ Metadata metadata = cluster.getMetadata();
5657 metadata.lock.lock();
5758 try {
5859 if (targetType == null || targetType == KEYSPACE) {
5960 // building the whole schema or a keyspace
6061 assert rows.keyspaces != null;
61- Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(metadata, rows, cassandraVersion);
62+ Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(rows, cassandraVersion, cluster);
6263 updateKeyspaces(metadata, metadata.keyspaces, keyspaces, targetKeyspace);
6364 } else {
6465 assert targetKeyspace != null;
@@ -73,64 +74,68 @@
7374 switch (targetType) {
7475 case TABLE:
7576 if (rows.tables.containsKey(targetKeyspace)) {
76- Map<String, TableMetadata> tables = buildTables(metadata, keyspace, rows.tables.get(targetKeyspace), rows.columns.get(targetKeyspace), rows.indexes.get(targetKeyspace), cassandraVersion);
77+ Map<String, TableMetadata> tables = buildTables(keyspace, rows.tables.get(targetKeyspace), rows.columns.get(targetKeyspace), rows.indexes.get(targetKeyspace), cassandraVersion, cluster);
7778 updateTables(metadata, keyspace.tables, tables, targetName);
7879 }
7980 if (rows.views.containsKey(targetKeyspace)) {
80- Map<String, MaterializedViewMetadata> tables = buildViews(keyspace, rows.views.get(targetKeyspace), rows.columns.get(targetKeyspace), cassandraVersion);
81+ Map<String, MaterializedViewMetadata> tables = buildViews(keyspace, rows.views.get(targetKeyspace), rows.columns.get(targetKeyspace), cassandraVersion, cluster);
8182 updateViews(metadata, keyspace.views, tables, targetName);
8283 }
8384 break;
8485 case TYPE:
8586 if (rows.udts.containsKey(targetKeyspace)) {
86- Map<String, UserType> userTypes = buildUserTypes(metadata, rows.udts.get(targetKeyspace));
87+ Map<String, UserType> userTypes = buildUserTypes(keyspace, rows.udts.get(targetKeyspace), cassandraVersion, cluster);
8788 updateUserTypes(metadata, keyspace.userTypes, userTypes, targetName);
8889 }
8990 break;
9091 case FUNCTION:
9192 if (rows.functions.containsKey(targetKeyspace)) {
92- Map<String, FunctionMetadata> functions = buildFunctions(metadata, keyspace, rows.functions.get(targetKeyspace));
93+ Map<String, FunctionMetadata> functions = buildFunctions(keyspace, rows.functions.get(targetKeyspace), cassandraVersion, cluster);
9394 updateFunctions(metadata, keyspace.functions, functions, targetName);
9495 }
9596 break;
9697 case AGGREGATE:
9798 if (rows.aggregates.containsKey(targetKeyspace)) {
98- Map<String, AggregateMetadata> aggregates = buildAggregates(metadata, keyspace, rows.aggregates.get(targetKeyspace));
99+ Map<String, AggregateMetadata> aggregates = buildAggregates(keyspace, rows.aggregates.get(targetKeyspace), cassandraVersion, cluster);
99100 updateAggregates(metadata, keyspace.aggregates, aggregates, targetName);
100101 }
101102 break;
102103 }
103104 }
104105 }
106+ } catch (RuntimeException e) {
107+ // Failure to parse the schema is definitively wrong so log a full-on error, but this won't generally prevent queries to
108+ // work and this can happen when new Cassandra versions modify stuff in the schema and the driver hasn't yet be modified.
109+ // So log, but let things go otherwise.
110+ logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e);
105111 } finally {
106112 metadata.lock.unlock();
107113 }
108114 }
109115
110- private Map<String, KeyspaceMetadata> buildKeyspaces(Metadata metadata,
111- SystemRows rows,
112- VersionNumber cassandraVersion) {
116+ private Map<String, KeyspaceMetadata> buildKeyspaces(SystemRows rows,
117+ VersionNumber cassandraVersion, Cluster cluster) {
113118
114119 Map<String, KeyspaceMetadata> keyspaces = new LinkedHashMap<String, KeyspaceMetadata>();
115120 for (Row keyspaceRow : rows.keyspaces) {
116121 KeyspaceMetadata keyspace = KeyspaceMetadata.build(keyspaceRow, cassandraVersion);
117- Map<String, TableMetadata> tables = buildTables(metadata, keyspace, rows.tables.get(keyspace.getName()), rows.columns.get(keyspace.getName()), rows.indexes.get(keyspace.getName()), cassandraVersion);
118- for (TableMetadata table : tables.values()) {
119- keyspace.add(table);
120- }
121- Map<String, UserType> userTypes = buildUserTypes(metadata, rows.udts.get(keyspace.getName()));
122+ Map<String, UserType> userTypes = buildUserTypes(keyspace, rows.udts.get(keyspace.getName()), cassandraVersion, cluster);
122123 for (UserType userType : userTypes.values()) {
123124 keyspace.add(userType);
124125 }
125- Map<String, FunctionMetadata> functions = buildFunctions(metadata, keyspace, rows.functions.get(keyspace.getName()));
126+ Map<String, TableMetadata> tables = buildTables(keyspace, rows.tables.get(keyspace.getName()), rows.columns.get(keyspace.getName()), rows.indexes.get(keyspace.getName()), cassandraVersion, cluster);
127+ for (TableMetadata table : tables.values()) {
128+ keyspace.add(table);
129+ }
130+ Map<String, FunctionMetadata> functions = buildFunctions(keyspace, rows.functions.get(keyspace.getName()), cassandraVersion, cluster);
126131 for (FunctionMetadata function : functions.values()) {
127132 keyspace.add(function);
128133 }
129- Map<String, AggregateMetadata> aggregates = buildAggregates(metadata, keyspace, rows.aggregates.get(keyspace.getName()));
134+ Map<String, AggregateMetadata> aggregates = buildAggregates(keyspace, rows.aggregates.get(keyspace.getName()), cassandraVersion, cluster);
130135 for (AggregateMetadata aggregate : aggregates.values()) {
131136 keyspace.add(aggregate);
132137 }
133- Map<String, MaterializedViewMetadata> views = buildViews(keyspace, rows.views.get(keyspace.getName()), rows.columns.get(keyspace.getName()), cassandraVersion);
138+ Map<String, MaterializedViewMetadata> views = buildViews(keyspace, rows.views.get(keyspace.getName()), rows.columns.get(keyspace.getName()), cassandraVersion, cluster);
134139 for (MaterializedViewMetadata view : views.values()) {
135140 keyspace.add(view);
136141 }
@@ -139,12 +144,9 @@
139144 return keyspaces;
140145 }
141146
142- private Map<String, TableMetadata> buildTables(Metadata metadata, KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, Map<String, List<Row>> indexDefs, VersionNumber cassandraVersion) {
147+ private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, Map<String, List<Row>> indexDefs, VersionNumber cassandraVersion, Cluster cluster) {
143148 Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>();
144149 if (tableRows != null) {
145- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
146- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
147-
148150 for (Row tableDef : tableRows) {
149151 String cfName = tableDef.getString(tableNameColumn());
150152 try {
@@ -169,10 +171,10 @@
169171 }
170172 }
171173 List<Row> cfIndexes = (indexDefs == null) ? null : indexDefs.get(cfName);
172- TableMetadata table = TableMetadata.build(keyspace, tableDef, cols, cfIndexes, tableNameColumn(), cassandraVersion, protocolVersion, codecRegistry);
174+ TableMetadata table = TableMetadata.build(keyspace, tableDef, cols, cfIndexes, tableNameColumn(), cassandraVersion, cluster);
173175 tables.put(table.getName(), table);
174176 } catch (RuntimeException e) {
175- // See ControlConnection#refreshSchema for why we'd rather not probably this further
177+ // See #refresh for why we'd rather not propagate this further
176178 logger.error(String.format("Error parsing schema for table %s.%s: "
177179 + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
178180 keyspace.getName(), cfName, keyspace.getName(), cfName), e);
@@ -182,26 +184,27 @@
182184 return tables;
183185 }
184186
185- private Map<String, UserType> buildUserTypes(Metadata metadata, List<Row> udtRows) {
187+ private Map<String, UserType> buildUserTypes(KeyspaceMetadata keyspace, List<Row> udtRows, VersionNumber cassandraVersion, Cluster cluster) {
186188 Map<String, UserType> userTypes = new LinkedHashMap<String, UserType>();
187189 if (udtRows != null) {
188- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
189- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
190- for (Row udtRow : udtRows) {
191- UserType type = UserType.build(udtRow, protocolVersion, codecRegistry);
190+ for (Row udtRow : maybeSortUdts(udtRows, cluster, keyspace.getName())) {
191+ UserType type = UserType.build(keyspace, udtRow, cassandraVersion, cluster, userTypes);
192192 userTypes.put(type.getTypeName(), type);
193193 }
194194 }
195195 return userTypes;
196196 }
197197
198- private Map<String, FunctionMetadata> buildFunctions(Metadata metadata, KeyspaceMetadata keyspace, List<Row> functionRows) {
198+ // Some schema versions require parsing UDTs in a specific order
199+ protected List<Row> maybeSortUdts(List<Row> udtRows, Cluster cluster, String keyspace) {
200+ return udtRows;
201+ }
202+
203+ private Map<String, FunctionMetadata> buildFunctions(KeyspaceMetadata keyspace, List<Row> functionRows, VersionNumber cassandraVersion, Cluster cluster) {
199204 Map<String, FunctionMetadata> functions = new LinkedHashMap<String, FunctionMetadata>();
200205 if (functionRows != null) {
201- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
202- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
203206 for (Row functionRow : functionRows) {
204- FunctionMetadata function = FunctionMetadata.build(keyspace, functionRow, protocolVersion, codecRegistry);
207+ FunctionMetadata function = FunctionMetadata.build(keyspace, functionRow, cassandraVersion, cluster);
205208 if (function != null)
206209 functions.put(function.getFullName(), function);
207210 }
@@ -209,13 +212,11 @@
209212 return functions;
210213 }
211214
212- private Map<String, AggregateMetadata> buildAggregates(Metadata metadata, KeyspaceMetadata keyspace, List<Row> aggregateRows) {
215+ private Map<String, AggregateMetadata> buildAggregates(KeyspaceMetadata keyspace, List<Row> aggregateRows, VersionNumber cassandraVersion, Cluster cluster) {
213216 Map<String, AggregateMetadata> aggregates = new LinkedHashMap<String, AggregateMetadata>();
214217 if (aggregateRows != null) {
215- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
216- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
217218 for (Row aggregateRow : aggregateRows) {
218- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, aggregateRow, protocolVersion, codecRegistry);
219+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, aggregateRow, cassandraVersion, cluster);
219220 if (aggregate != null)
220221 aggregates.put(aggregate.getFullName(), aggregate);
221222 }
@@ -223,7 +224,7 @@
223224 return aggregates;
224225 }
225226
226- private Map<String, MaterializedViewMetadata> buildViews(KeyspaceMetadata keyspace, List<Row> viewRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
227+ private Map<String, MaterializedViewMetadata> buildViews(KeyspaceMetadata keyspace, List<Row> viewRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion, Cluster cluster) {
227228 Map<String, MaterializedViewMetadata> views = new LinkedHashMap<String, MaterializedViewMetadata>();
228229 if (viewRows != null) {
229230 for (Row viewRow : viewRows) {
@@ -233,11 +234,11 @@
233234 if (cols == null || cols.isEmpty())
234235 continue; // we probably raced, we will update the metadata next time
235236
236- MaterializedViewMetadata view = MaterializedViewMetadata.build(keyspace, viewRow, cols, cassandraVersion);
237+ MaterializedViewMetadata view = MaterializedViewMetadata.build(keyspace, viewRow, cols, cassandraVersion, cluster);
237238 if(view != null)
238239 views.put(view.getName(), view);
239240 } catch (RuntimeException e) {
240- // See ControlConnection#refreshSchema for why we'd rather not probably this further
241+ // See #refresh for why we'd rather not propagate this further
241242 logger.error(String.format("Error parsing schema for view %s.%s: "
242243 + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will be missing or incomplete",
243244 keyspace.getName(), viewName, keyspace.getName(), viewName), e);
@@ -423,7 +424,7 @@
423424 return result;
424425 }
425426
426- static Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndCf(ResultSet rs, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String tableName) {
427+ static Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndCf(ResultSet rs, VersionNumber cassandraVersion, String tableName) {
427428 if (rs == null)
428429 return Collections.emptyMap();
429430
@@ -442,7 +443,7 @@
442443 l = new HashMap<String, ColumnMetadata.Raw>();
443444 colsByCf.put(cfName, l);
444445 }
445- ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, protocolVersion, codecRegistry);
446+ ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion);
446447 l.put(c.name, c);
447448 }
448449 return result;
@@ -497,14 +498,12 @@
497498 private static final String CF_NAME = "columnfamily_name";
498499
499500 @Override
500- SystemRows fetchSystemRows(Metadata metadata,
501+ SystemRows fetchSystemRows(Cluster cluster,
501502 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
502503 Connection connection, VersionNumber cassandraVersion)
503504 throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
504505
505506 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
506- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
507- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
508507
509508 String whereClause = "";
510509 if (targetType != null) {
@@ -526,6 +525,8 @@
526525 functionsFuture = null,
527526 aggregatesFuture = null;
528527
528+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
529+
529530 if (isSchemaOrKeyspace)
530531 ksFuture = queryAsync(SELECT_KEYSPACES + whereClause, connection, protocolVersion);
531532
@@ -545,7 +546,7 @@
545546
546547 return new SystemRows(get(ksFuture),
547548 groupByKeyspace(get(cfFuture)),
548- groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, CF_NAME),
549+ groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, CF_NAME),
549550 groupByKeyspace(get(udtFuture)),
550551 groupByKeyspace(get(functionsFuture)),
551552 groupByKeyspace(get(aggregatesFuture)),
@@ -583,12 +584,10 @@
583584 private static final String TABLE_NAME = "table_name";
584585
585586 @Override
586- SystemRows fetchSystemRows(Metadata metadata, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Connection connection, VersionNumber cassandraVersion)
587+ SystemRows fetchSystemRows(Cluster cluster, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Connection connection, VersionNumber cassandraVersion)
587588 throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
588589
589590 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
590- ProtocolVersion protocolVersion = metadata.cluster.protocolVersion();
591- CodecRegistry codecRegistry = metadata.cluster.configuration.getCodecRegistry();
592591
593592 ResultSetFuture ksFuture = null,
594593 udtFuture = null,
@@ -599,6 +598,8 @@
599598 indexesFuture = null,
600599 viewsFuture = null;
601600
601+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
602+
602603 if (isSchemaOrKeyspace)
603604 ksFuture = queryAsync(SELECT_KEYSPACES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
604605
@@ -620,7 +621,7 @@
620621
621622 return new SystemRows(get(ksFuture),
622623 groupByKeyspace(get(cfFuture)),
623- groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, protocolVersion, codecRegistry, TABLE_NAME),
624+ groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, TABLE_NAME),
624625 groupByKeyspace(get(udtFuture)),
625626 groupByKeyspace(get(functionsFuture)),
626627 groupByKeyspace(get(aggregatesFuture)),
@@ -644,12 +645,57 @@
644645 else if (targetType == TYPE)
645646 whereClause += " AND type_name = '" + targetName + '\'';
646647 else if (targetType == FUNCTION)
647- whereClause += " AND function_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
648+ whereClause += " AND function_name = '" + targetName + "' AND argument_types = " + LIST_OF_TEXT_CODEC.format(targetSignature);
648649 else if (targetType == AGGREGATE)
649- whereClause += " AND aggregate_name = '" + targetName + "' AND signature = " + LIST_OF_TEXT_CODEC.format(targetSignature);
650+ whereClause += " AND aggregate_name = '" + targetName + "' AND argument_types = " + LIST_OF_TEXT_CODEC.format(targetSignature);
650651 }
651652 return whereClause;
652653 }
653654
655+
656+ @Override
657+ protected List<Row> maybeSortUdts(List<Row> udtRows, Cluster cluster, String keyspace) {
658+ if (udtRows.size() < 2)
659+ return udtRows;
660+
661+ // For C* 3+, user-defined type resolution must be done in proper order
662+ // to guarantee that nested UDTs get resolved
663+ DirectedGraph<Row> graph = new DirectedGraph<Row>(udtRows);
664+ for (Row from : udtRows) {
665+ for (Row to : udtRows) {
666+ if (from != to && dependsOn(to, from, cluster, keyspace))
667+ graph.addEdge(from, to);
668+ }
669+ }
670+ return graph.topologicalSort();
671+ }
672+
673+ private boolean dependsOn(Row udt1, Row udt2, Cluster cluster, String keyspace) {
674+ List<String> fieldTypes = udt1.getList(UserType.COLS_TYPES, String.class);
675+ String typeName = udt2.getString(UserType.TYPE_NAME);
676+ for (String fieldTypeStr : fieldTypes) {
677+ // use shallow user types since some definitions might not be known at this stage
678+ DataType fieldType = DataTypeCqlNameParser.parse(fieldTypeStr, cluster, keyspace, null, null, false, true);
679+ if (references(fieldType, typeName))
680+ return true;
681+ }
682+ return false;
683+ }
684+
685+ private boolean references(DataType dataType, String typeName) {
686+ if (dataType instanceof UserType.Shallow && ((UserType.Shallow)dataType).typeName.equals(typeName))
687+ return true;
688+ for (DataType arg : dataType.getTypeArguments()) {
689+ if (references(arg, typeName))
690+ return true;
691+ }
692+ if (dataType instanceof TupleType) {
693+ for (DataType arg : ((TupleType)dataType).getComponentTypes()) {
694+ if (references(arg, typeName))
695+ return true;
696+ }
697+ }
698+ return false;
699+ }
654700 }
655701 }
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +23 −12
@@ -48,7 +48,7 @@
4848 private static final String SUPER = "super";
4949 private static final String COMPOUND = "compound";
5050
51- private static final String EMPTY_TYPE = "org.apache.cassandra.db.marshal.EmptyType";
51+ private static final String EMPTY_TYPE = "empty";
5252
5353 private final Map<String, IndexMetadata> indexes;
5454
@@ -69,7 +69,7 @@
6969 this.views = new HashMap<String, MaterializedViewMetadata>();
7070 }
7171
72- static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, List<Row> indexRows, String nameColumn, VersionNumber cassandraVersion, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
72+ static TableMetadata build(KeyspaceMetadata ksm, Row row, Map<String, ColumnMetadata.Raw> rawCols, List<Row> indexRows, String nameColumn, VersionNumber cassandraVersion, Cluster cluster) {
7373
7474 String name = row.getString(nameColumn);
7575
@@ -80,13 +80,16 @@
8080 else if (cassandraVersion.getMajor() > 2)
8181 id = row.getUUID(CF_ID_V3);
8282
83- CassandraTypeParser.ParseResult comparator = null;
84- CassandraTypeParser.ParseResult keyValidator = null;
83+ DataTypeClassNameParser.ParseResult comparator = null;
84+ DataTypeClassNameParser.ParseResult keyValidator = null;
8585 List<String> columnAliases = null;
8686
87+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
88+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
89+
8790 if (cassandraVersion.getMajor() <= 2) {
88- comparator = CassandraTypeParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
89- keyValidator = CassandraTypeParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
91+ comparator = DataTypeClassNameParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
92+ keyValidator = DataTypeClassNameParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
9093 columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
9194 ? Collections.<String>emptyList()
9295 : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
@@ -173,14 +176,20 @@
173176 String alias = row.isNull(VALUE_ALIAS) ? DEFAULT_VALUE_ALIAS : row.getString(VALUE_ALIAS);
174177 // ...unless the table does not have any regular column, only primary key columns (JAVA-873)
175178 if (!alias.isEmpty()) {
176- DataType type = CassandraTypeParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
179+ DataType type = DataTypeClassNameParser.parseOne(row.getString(VALIDATOR), protocolVersion, codecRegistry);
177180 otherColumns.add(ColumnMetadata.forAlias(tm, alias, type));
178181 }
179182 }
180183 }
181184
182185 for (ColumnMetadata.Raw rawCol : rawCols.values()) {
183- ColumnMetadata col = ColumnMetadata.fromRaw(tm, rawCol);
186+ DataType dataType;
187+ if(cassandraVersion.getMajor() >= 3) {
188+ dataType = DataTypeCqlNameParser.parse(rawCol.dataType, cluster, ksm.getName(), ksm.userTypes, null, false, false);
189+ } else {
190+ dataType = DataTypeClassNameParser.parseOne(rawCol.dataType, protocolVersion, codecRegistry);
191+ }
192+ ColumnMetadata col = ColumnMetadata.fromRaw(tm, rawCol, dataType);
184193 switch (rawCol.kind) {
185194 case PARTITION_KEY:
186195 partitionKey.set(rawCol.position, col);
@@ -250,8 +259,9 @@
250259 Iterator<ColumnMetadata.Raw> it = cols.iterator();
251260 while(it.hasNext()) {
252261 ColumnMetadata.Raw col = it.next();
253- if(col.kind == ColumnMetadata.Raw.Kind.REGULAR && col.dataType instanceof DataType.CustomType && EMPTY_TYPE.equals(((DataType.CustomType)col.dataType).getCustomTypeClassName())) {
254- // remove "value EmptyType" regular column
262+ if (col.kind == ColumnMetadata.Raw.Kind.REGULAR
263+ && col.dataType.equals(EMPTY_TYPE)) {
264+ // remove "value empty" regular column
255265 it.remove();
256266 }
257267 }
@@ -271,7 +281,7 @@
271281 return rawCols;
272282 }
273283
274- private static int findPartitionKeySize(Collection<ColumnMetadata.Raw> cols, CassandraTypeParser.ParseResult keyValidator) {
284+ private static int findPartitionKeySize(Collection<ColumnMetadata.Raw> cols, DataTypeClassNameParser.ParseResult keyValidator) {
275285 // C* 1.2, 2.0, 2.1 and 2.2
276286 if(keyValidator != null)
277287 return keyValidator.types.size();
@@ -283,7 +293,7 @@
283293 return maxId + 1;
284294 }
285295
286- private static int findClusteringSize(CassandraTypeParser.ParseResult comparator,
296+ private static int findClusteringSize(DataTypeClassNameParser.ParseResult comparator,
287297 Collection<ColumnMetadata.Raw> cols,
288298 List<String> columnAliases,
289299 VersionNumber cassandraVersion) {
@@ -385,6 +395,7 @@
385395 return sb.toString();
386396 }
387397
398+ @Override
388399 protected String asCQLQuery(boolean formatted) {
389400 StringBuilder sb = new StringBuilder();
390401 sb.append("CREATE TABLE ").append(Metadata.escapeId(keyspace.getName())).append('.').append(Metadata.escapeId(name)).append(" (");
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +3 −3
@@ -30,11 +30,11 @@
3030 }
3131
3232 protected DataType getType(int i) {
33- return definition.byIdx[i].getType();
33+ return definition.getFields()[i].getType();
3434 }
3535
3636 protected String getName(int i) {
37- return definition.byIdx[i].getName();
37+ return definition.getFields()[i].getName();
3838 }
3939
4040 @Override
@@ -43,7 +43,7 @@
4343 }
4444
4545 protected int[] getAllIndexesOf(String name) {
46- int[] indexes = definition.byName.get(Metadata.handleId(name));
46+ int[] indexes = definition.getFieldIndicesByName().get(Metadata.handleId(name));
4747 if (indexes == null)
4848 throw new IllegalArgumentException(name + " is not a field defined in this UDT");
4949 return indexes;
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +55 −13
@@ -25,11 +25,11 @@
2525 * <p>
2626 * A UDT is a essentially a named collection of fields (with a name and a type).
2727 */
28-public class UserType extends DataType implements Iterable<UserType.Field>{
28+public class UserType extends DataType implements Iterable<UserType.Field> {
2929
30- private static final String TYPE_NAME = "type_name";
30+ static final String TYPE_NAME = "type_name";
3131 private static final String COLS_NAMES = "field_names";
32- private static final String COLS_TYPES = "field_types";
32+ static final String COLS_TYPES = "field_types";
3333
3434 private final String keyspace;
3535 private final String typeName;
@@ -40,11 +40,11 @@
4040 // Note that we don't expose the order of fields, from an API perspective this is a map
4141 // of String->Field, but internally we care about the order because the serialization format
4242 // of UDT expects a particular order.
43- final Field[] byIdx;
43+ private final Field[] byIdx;
4444 // For a given name, we can only have one field with that name, so we don't need a int[] in
4545 // practice. However, storing one element arrays save allocations in UDTValue.getAllIndexesOf
4646 // implementation.
47- final Map<String, int[]> byName;
47+ private final Map<String, int[]> byName;
4848
4949 UserType(String keyspace, String typeName, Collection<Field> fields, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5050 super(DataType.Name.UDT);
@@ -62,7 +62,10 @@
6262 this.byName = builder.build();
6363 }
6464
65- static UserType build(Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
65+ static UserType build(KeyspaceMetadata ksm, Row row, VersionNumber version, Cluster cluster, Map<String, UserType> userTypes) {
66+ ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
67+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
68+
6669 String keyspace = row.getString(KeyspaceMetadata.KS_NAME);
6770 String name = row.getString(TYPE_NAME);
6871
@@ -70,9 +73,15 @@
7073 List<String> fieldTypes = row.getList(COLS_TYPES, String.class);
7174
7275 List<Field> fields = new ArrayList<Field>(fieldNames.size());
73- for (int i = 0; i < fieldNames.size(); i++)
74- fields.add(new Field(fieldNames.get(i), CassandraTypeParser.parseOne(fieldTypes.get(i), protocolVersion, codecRegistry)));
75-
76+ for (int i = 0; i < fieldNames.size(); i++) {
77+ DataType fieldType;
78+ if (version.getMajor() >= 3.0) {
79+ fieldType = DataTypeCqlNameParser.parse(fieldTypes.get(i), cluster, ksm.getName(), userTypes, ksm.userTypes, false, false);
80+ } else {
81+ fieldType = DataTypeClassNameParser.parseOne(fieldTypes.get(i), protocolVersion, codecRegistry);
82+ }
83+ fields.add(new Field(fieldNames.get(i), fieldType));
84+ }
7685 return new UserType(keyspace, name, fields, protocolVersion, codecRegistry);
7786 }
7887
@@ -169,6 +178,14 @@
169178 return true;
170179 }
171180
181+ Field[] getFields() {
182+ return byIdx;
183+ }
184+
185+ Map<String, int[]> getFieldIndicesByName() {
186+ return byName;
187+ }
188+
172189 @Override
173190 public int hashCode() {
174191 int result = name.hashCode();
@@ -179,8 +196,8 @@
179196 }
180197
181198 @Override
182- public final boolean equals(Object o) {
183- if(!(o instanceof UserType))
199+ public boolean equals(Object o) {
200+ if (!(o instanceof UserType))
184201 return false;
185202
186203 UserType other = (UserType)o;
@@ -190,7 +207,7 @@
190207 return name.equals(other.name)
191208 && keyspace.equals(other.keyspace)
192209 && typeName.equals(other.typeName)
193- && Arrays.equals(byIdx, other.byIdx);
210+ && Arrays.equals(getFields(), other.getFields());
194211 }
195212
196213 /**
@@ -301,7 +318,7 @@
301318
302319 @Override
303320 public final boolean equals(Object o) {
304- if(!(o instanceof Field))
321+ if (!(o instanceof Field))
305322 return false;
306323
307324 Field other = (Field)o;
@@ -314,4 +331,29 @@
314331 return Metadata.escapeId(name) + ' ' + type;
315332 }
316333 }
334+
335+ /**
336+ * A "shallow" definition of a UDT that only contains the keyspace and type name, without any information
337+ * about the type's structure.
338+ *
339+ * This is used for internal dependency analysis only, and never returned to the client.
340+ *
341+ * @since 3.0.0
342+ */
343+ static class Shallow extends DataType {
344+
345+ final String keyspaceName;
346+ final String typeName;
347+
348+ Shallow(String keyspaceName, String typeName) {
349+ super(Name.UDT);
350+ this.keyspaceName = keyspaceName;
351+ this.typeName = typeName;
352+ }
353+
354+ @Override
355+ public boolean isFrozen() {
356+ return false;
357+ }
358+ }
317359 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java +52 −0
@@ -0,0 +1,52 @@
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.exceptions;
17+
18+/**
19+ * Thrown when a user type cannot be resolved.
20+ */
21+public class UnresolvedUserTypeException extends InvalidTypeException {
22+
23+ private final String keyspaceName;
24+
25+ private final String name;
26+
27+ public UnresolvedUserTypeException(String keyspaceName, String name) {
28+ super(String.format("Cannot resolve user type %s.%s", keyspaceName, name));
29+ this.keyspaceName = keyspaceName;
30+ this.name = name;
31+ }
32+
33+ private UnresolvedUserTypeException(String keyspaceName, String name, Throwable cause) {
34+ super(String.format("Cannot resolve user type %s.%s", keyspaceName, name), cause);
35+ this.keyspaceName = keyspaceName;
36+ this.name = name;
37+ }
38+
39+ public String getKeyspaceName() {
40+ return keyspaceName;
41+ }
42+
43+ public String getName() {
44+ return name;
45+ }
46+
47+ @Override
48+ public DriverException copy() {
49+ return new UnresolvedUserTypeException(keyspaceName, name, this);
50+ }
51+
52+}
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +80 −113
@@ -15,167 +15,134 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
18+import java.util.Collection;
1919 import java.util.Collections;
20-import java.util.List;
2120
22-import com.google.common.collect.ImmutableList;
23-import org.testng.annotations.BeforeMethod;
2421 import org.testng.annotations.Test;
2522
26-import static org.mockito.Mockito.mock;
27-import static org.mockito.Mockito.when;
23+import com.datastax.driver.core.utils.CassandraVersion;
2824
2925 import static com.datastax.driver.core.Assertions.assertThat;
26+import static com.datastax.driver.core.DataType.cint;
27+import static com.datastax.driver.core.DataType.text;
3028
31-public class AggregateMetadataTest {
29+@CassandraVersion(major = 2.2)
30+public class AggregateMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3231
33- // These tests needs a protocol version to (de)serialize INITCONDs. Since we're using basic types, I don't think the binary format
34- // is going to change at any time in the future, so the actual version does not matter.
35- private static final ProtocolVersion PROTOCOL_VERSION = ProtocolVersion.NEWEST_SUPPORTED;
36- private CodecRegistry codecRegistry = new CodecRegistry();
37-
38- KeyspaceMetadata keyspace;
39-
40- @BeforeMethod(groups = "unit")
41- public void setup() {
42- keyspace = new KeyspaceMetadata("ks", false, Collections.<String, String>emptyMap());
43- }
44-
45- @Test(groups = "unit")
32+ @Test(groups = "short")
4633 public void should_parse_and_format_aggregate_with_initcond_and_no_finalfunc() {
47- FunctionMetadata stateFunc = mock(FunctionMetadata.class);
48- keyspace.functions.put("cat(text,int)", stateFunc);
49-
50- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_CAT_TOS, PROTOCOL_VERSION, codecRegistry);
51-
34+ // given
35+ String cqlFunction = String.format("CREATE FUNCTION %s.cat(s text,v int) RETURNS NULL ON NULL INPUT RETURNS text LANGUAGE java AS 'return s+v;';", keyspace);
36+ String cqlAggregate = String.format("CREATE AGGREGATE %s.cat_tos(int) SFUNC cat STYPE text INITCOND '0';", keyspace);
37+ // when
38+ session.execute(cqlFunction);
39+ session.execute(cqlAggregate);
40+ // then
41+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
42+ FunctionMetadata stateFunc = keyspace.getFunction("cat", text(), cint());
43+ AggregateMetadata aggregate = keyspace.getAggregate("cat_tos", cint());
5244 assertThat(aggregate).isNotNull();
5345 assertThat(aggregate.getFullName()).isEqualTo("cat_tos(int)");
5446 assertThat(aggregate.getSimpleName()).isEqualTo("cat_tos");
55- assertThat(aggregate.getArgumentTypes()).containsExactly(DataType.cint());
47+ assertThat(aggregate.getArgumentTypes()).containsExactly(cint());
5648 assertThat(aggregate.getFinalFunc()).isNull();
5749 assertThat(aggregate.getInitCond()).isEqualTo("0");
58- assertThat(aggregate.getReturnType()).isEqualTo(DataType.text());
50+ assertThat(aggregate.getReturnType()).isEqualTo(text());
5951 assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc);
60- assertThat(aggregate.getStateType()).isEqualTo(DataType.text());
61-
62- assertThat(keyspace.getAggregate("cat_tos", DataType.cint())).isEqualTo(aggregate);
63-
64- assertThat(aggregate.toString()).isEqualTo("CREATE AGGREGATE ks.cat_tos(int) SFUNC cat STYPE text INITCOND '0';");
65-
66- assertThat(aggregate.exportAsString()).isEqualTo("CREATE AGGREGATE ks.cat_tos(int)\n"
52+ assertThat(aggregate.getStateType()).isEqualTo(text());
53+ assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
54+ assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.cat_tos(int)\n"
6755 + "SFUNC cat STYPE text\n"
68- + "INITCOND '0';");
56+ + "INITCOND '0';", this.keyspace));
6957 }
7058
71- @Test(groups = "unit")
59+ @Test(groups = "short")
7260 public void should_parse_and_format_aggregate_with_no_arguments() {
73- FunctionMetadata stateFunc = mock(FunctionMetadata.class);
74- keyspace.functions.put("inc(int)", stateFunc);
75-
76- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_MYCOUNT, PROTOCOL_VERSION, codecRegistry);
77-
61+ // given
62+ String cqlFunction = String.format("CREATE FUNCTION %s.inc(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i+1;';", keyspace);
63+ String cqlAggregate = String.format("CREATE AGGREGATE %s.mycount() SFUNC inc STYPE int INITCOND 0;", keyspace);
64+ // when
65+ session.execute(cqlFunction);
66+ session.execute(cqlAggregate);
67+ // then
68+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
69+ FunctionMetadata stateFunc = keyspace.getFunction("inc", cint());
70+ AggregateMetadata aggregate = keyspace.getAggregate("mycount");
7871 assertThat(aggregate).isNotNull();
7972 assertThat(aggregate.getFullName()).isEqualTo("mycount()");
8073 assertThat(aggregate.getSimpleName()).isEqualTo("mycount");
8174 assertThat(aggregate.getArgumentTypes()).isEmpty();
8275 assertThat(aggregate.getFinalFunc()).isNull();
8376 assertThat(aggregate.getInitCond()).isEqualTo(0);
84- assertThat(aggregate.getReturnType()).isEqualTo(DataType.cint());
77+ assertThat(aggregate.getReturnType()).isEqualTo(cint());
8578 assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc);
86- assertThat(aggregate.getStateType()).isEqualTo(DataType.cint());
87-
88- assertThat(keyspace.getAggregate("mycount")).isEqualTo(aggregate);
89-
90- assertThat(aggregate.toString()).isEqualTo("CREATE AGGREGATE ks.mycount() SFUNC inc STYPE int INITCOND 0;");
91-
92- assertThat(aggregate.exportAsString()).isEqualTo("CREATE AGGREGATE ks.mycount()\n"
79+ assertThat(aggregate.getStateType()).isEqualTo(cint());
80+ assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
81+ assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.mycount()\n"
9382 + "SFUNC inc STYPE int\n"
94- + "INITCOND 0;");
83+ + "INITCOND 0;", this.keyspace));
9584 }
9685
97- @Test(groups = "unit")
86+ @Test(groups = "short")
9887 public void should_parse_and_format_aggregate_with_final_function() {
99- FunctionMetadata stateFunc = mock(FunctionMetadata.class);
100- keyspace.functions.put("plus(int,int)", stateFunc);
101- FunctionMetadata finalFunc = mock(FunctionMetadata.class);
102- keyspace.functions.put("announce(int)", finalFunc);
103-
104- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_PRETTYSUM, PROTOCOL_VERSION, codecRegistry);
105-
88+ // given
89+ String cqlFunction1 = String.format("CREATE FUNCTION %s.plus(i int, j int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i+j;';", keyspace);
90+ String cqlFunction2 = String.format("CREATE FUNCTION %s.announce(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;';", keyspace);
91+ String cqlAggregate = String.format("CREATE AGGREGATE %s.prettysum(int) SFUNC plus STYPE int FINALFUNC announce INITCOND 0;", keyspace);
92+ // when
93+ session.execute(cqlFunction1);
94+ session.execute(cqlFunction2);
95+ session.execute(cqlAggregate);
96+ // then
97+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
98+ FunctionMetadata stateFunc = keyspace.getFunction("plus", cint(), cint());
99+ FunctionMetadata finalFunc = keyspace.getFunction("announce", cint());
100+ AggregateMetadata aggregate = keyspace.getAggregate("prettysum", cint());
106101 assertThat(aggregate).isNotNull();
107102 assertThat(aggregate.getFullName()).isEqualTo("prettysum(int)");
108103 assertThat(aggregate.getSimpleName()).isEqualTo("prettysum");
109- assertThat(aggregate.getArgumentTypes()).containsExactly(DataType.cint());
104+ assertThat(aggregate.getArgumentTypes()).containsExactly(cint());
110105 assertThat(aggregate.getFinalFunc()).isEqualTo(finalFunc);
111106 assertThat(aggregate.getInitCond()).isEqualTo(0);
112- assertThat(aggregate.getReturnType()).isEqualTo(DataType.text());
107+ assertThat(aggregate.getReturnType()).isEqualTo(cint());
113108 assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc);
114- assertThat(aggregate.getStateType()).isEqualTo(DataType.cint());
115-
116- assertThat(keyspace.getAggregate("prettysum", DataType.cint())).isEqualTo(aggregate);
117-
118- assertThat(aggregate.toString()).isEqualTo("CREATE AGGREGATE ks.prettysum(int) SFUNC plus STYPE int FINALFUNC announce INITCOND 0;");
119-
120- assertThat(aggregate.exportAsString()).isEqualTo("CREATE AGGREGATE ks.prettysum(int)\n"
109+ assertThat(aggregate.getStateType()).isEqualTo(cint());
110+ assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
111+ assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.prettysum(int)\n"
121112 + "SFUNC plus STYPE int\n"
122113 + "FINALFUNC announce\n"
123- + "INITCOND 0;");
114+ + "INITCOND 0;", this.keyspace));
124115 }
125116
126- @Test(groups = "unit")
117+ @Test(groups = "short")
127118 public void should_parse_and_format_aggregate_with_no_initcond() {
128- FunctionMetadata stateFunc = mock(FunctionMetadata.class);
129- keyspace.functions.put("plus(int,int)", stateFunc);
130-
131- AggregateMetadata aggregate = AggregateMetadata.build(keyspace, SYSTEM_ROW_SUM, PROTOCOL_VERSION, codecRegistry);
132-
119+ // given
120+ String cqlFunction = String.format("CREATE FUNCTION %s.plus2(i int, j int) CALLED ON NULL INPUT RETURNS int LANGUAGE java AS 'return i+j;';", keyspace);
121+ String cqlAggregate = String.format("CREATE AGGREGATE %s.sum(int) SFUNC plus2 STYPE int;", keyspace);
122+ // when
123+ session.execute(cqlFunction);
124+ session.execute(cqlAggregate);
125+ // then
126+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
127+ FunctionMetadata stateFunc = keyspace.getFunction("plus2", cint(), cint());
128+ AggregateMetadata aggregate = keyspace.getAggregate("sum", cint());
133129 assertThat(aggregate).isNotNull();
134130 assertThat(aggregate.getFullName()).isEqualTo("sum(int)");
135131 assertThat(aggregate.getSimpleName()).isEqualTo("sum");
136- assertThat(aggregate.getArgumentTypes()).containsExactly(DataType.cint());
132+ assertThat(aggregate.getArgumentTypes()).containsExactly(cint());
137133 assertThat(aggregate.getFinalFunc()).isNull();
138134 assertThat(aggregate.getInitCond()).isNull();
139- assertThat(aggregate.getReturnType()).isEqualTo(DataType.cint());
135+ assertThat(aggregate.getReturnType()).isEqualTo(cint());
140136 assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc);
141- assertThat(aggregate.getStateType()).isEqualTo(DataType.cint());
142-
143- assertThat(keyspace.getAggregate("sum", DataType.cint())).isEqualTo(aggregate);
144-
145- assertThat(aggregate.toString()).isEqualTo("CREATE AGGREGATE ks.sum(int) SFUNC plus STYPE int;");
146-
147- assertThat(aggregate.exportAsString()).isEqualTo("CREATE AGGREGATE ks.sum(int)\n"
148- + "SFUNC plus STYPE int;");
137+ assertThat(aggregate.getStateType()).isEqualTo(cint());
138+ assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
139+ assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.sum(int)\n"
140+ + "SFUNC plus2 STYPE int;", this.keyspace));
149141 }
150142
151- private static final String INT = "org.apache.cassandra.db.marshal.Int32Type";
152- private static final String TEXT = "org.apache.cassandra.db.marshal.UTF8Type";
153-
154- private static final Row SYSTEM_ROW_CAT_TOS = mockRow("cat_tos", ImmutableList.of("int"), ImmutableList.of(INT),
155- null, TypeCodec.varchar().serialize("0", PROTOCOL_VERSION), TEXT, "cat", TEXT);
156-
157- private static final Row SYSTEM_ROW_MYCOUNT = mockRow("mycount", Collections.<String>emptyList(), Collections.<String>emptyList(),
158- null, TypeCodec.cint().serialize(0, PROTOCOL_VERSION), INT, "inc", INT);
159-
160- private static final Row SYSTEM_ROW_PRETTYSUM = mockRow("prettysum", ImmutableList.of("int"), ImmutableList.of(INT),
161- "announce", TypeCodec.cint().serialize(0, PROTOCOL_VERSION), TEXT, "plus", INT);
162-
163- private static final Row SYSTEM_ROW_SUM = mockRow("sum", ImmutableList.of("int"), ImmutableList.of(INT),
164- null, null, INT, "plus", INT);
165-
166- private static Row mockRow(String aggregateName, List<String> signature, List<String> argumentTypes, String finalFunc,
167- ByteBuffer initCond, String returnType, String stateFunc, String stateType) {
168- Row row = mock(Row.class);
169-
170- when(row.getString("aggregate_name")).thenReturn(aggregateName);
171- when(row.getList("signature", String.class)).thenReturn(signature);
172- when(row.getList("argument_types", String.class)).thenReturn(argumentTypes);
173- when(row.getString("final_func")).thenReturn(finalFunc);
174- when(row.getBytes("initcond")).thenReturn(initCond);
175- when(row.getString("return_type")).thenReturn(returnType);
176- when(row.getString("state_func")).thenReturn(stateFunc);
177- when(row.getString("state_type")).thenReturn(stateType);
178-
179- return row;
143+ @Override
144+ protected Collection<String> getTableDefinitions() {
145+ return Collections.emptyList();
180146 }
147+
181148 }
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +9 −0
@@ -35,6 +35,15 @@
3535 return new DataTypeAssert(type);
3636 }
3737
38+ /**
39+ * This method is here only to disambiguate
40+ * calls to assertThat with a UserType instance,
41+ * because UserType also implements Iterable.
42+ */
43+ public static DataTypeAssert assertThat(UserType type) {
44+ return new DataTypeAssert(type);
45+ }
46+
3847 public static LocalDateAssert assertThat(LocalDate localDate) {
3948 return new LocalDateAssert(localDate);
4049 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +1 −1
@@ -103,7 +103,7 @@
103103 if (installDirectory != null && !installDirectory.trim().isEmpty()) {
104104 CASSANDRA_INSTALL_ARGS = "--install-dir=" + new File(installDirectory).getAbsolutePath();
105105 } else if(branch != null && !branch.trim().isEmpty()) {
106- CASSANDRA_INSTALL_ARGS = "-v git:" + branch;
106+ CASSANDRA_INSTALL_ARGS = "-v " + branch.replaceAll("\"", "");
107107 } else {
108108 CASSANDRA_INSTALL_ARGS = "-v " + CASSANDRA_VERSION;
109109 }
deleted driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +0 −139
@@ -1,139 +0,0 @@
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.Arrays;
19-import java.util.Iterator;
20-
21-import org.testng.annotations.Test;
22-
23-import static org.testng.Assert.assertEquals;
24-import static org.testng.Assert.assertFalse;
25-import static org.testng.Assert.assertNotNull;
26-import static org.testng.Assert.assertTrue;
27-
28-import static com.datastax.driver.core.Assertions.assertThat;
29-
30-public class CassandraTypeParserTest {
31-
32- private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
33- private CodecRegistry codecRegistry = new CodecRegistry();
34-
35- @Test(groups = "unit")
36- public void parseOneTest() {
37-
38- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ByteType", protocolVersion, codecRegistry), DataType.tinyint());
39- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ShortType", protocolVersion, codecRegistry), DataType.smallint());
40- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.SimpleDateType", protocolVersion, codecRegistry), DataType.date());
41- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.TimeType", protocolVersion, codecRegistry), DataType.time());
42- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.InetAddressType", protocolVersion, codecRegistry), DataType.inet());
43- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.list(DataType.text()));
44- assertEquals(CassandraTypeParser.parseOne("org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.text());
45-
46- String s;
47-
48- s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type, org.apache.cassandra.db.marshal.Int32Type)";
49- assertEquals(CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry), DataType.custom(s));
50-
51- s = "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type))";
52- assertEquals(CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry), DataType.list(DataType.cint()));
53- }
54-
55- @Test(groups = "unit")
56- public void parseWithCompositeTest() {
57-
58- String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,";
59- s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
60- CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s, protocolVersion, codecRegistry);
61- assertTrue(r1.isComposite);
62- assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text()));
63- assertEquals(r1.collections.size(), 1);
64- assertEquals(r1.collections.get("ab"), DataType.list(DataType.cint()));
65-
66- CassandraTypeParser.ParseResult r2 = CassandraTypeParser.parseWithComposite("org.apache.cassandra.db.marshal.TimestampType", protocolVersion, codecRegistry);
67- assertFalse(r2.isComposite);
68- assertEquals(r2.types, Arrays.asList(DataType.timestamp()));
69- assertEquals(r2.collections.size(), 0);
70- }
71-
72- @Test(groups = "unit")
73- public void parseUserTypes() {
74-
75- String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))";
76- UserType def = (UserType)CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
77-
78- assertEquals(def.getKeyspace(), "foo");
79- assertEquals(def.getTypeName(), "address");
80-
81- Iterator<UserType.Field> iter = def.iterator();
82-
83- UserType.Field field1 = iter.next();
84- assertEquals(field1.getName(), "street");
85- assertEquals(field1.getType(), DataType.text());
86-
87- UserType.Field field2 = iter.next();
88- assertEquals(field2.getName(), "zipcode");
89- assertEquals(field2.getType(), DataType.cint());
90-
91- UserType.Field field3 = iter.next();
92- assertEquals(field3.getName(), "phones");
93-
94- DataType st = field3.getType();
95- assertEquals(st.getName(), DataType.Name.SET);
96- UserType subDef = (UserType)st.getTypeArguments().get(0);
97-
98- assertEquals(subDef.getKeyspace(), "foo");
99- assertEquals(subDef.getTypeName(), "phone");
100-
101- Iterator<UserType.Field> subIter = subDef.iterator();
102-
103- UserType.Field subField1 = subIter.next();
104- assertEquals(subField1.getName(), "name");
105- assertEquals(subField1.getType(), DataType.text());
106-
107- UserType.Field subField2 = subIter.next();
108- assertEquals(subField2.getName(), "number");
109- assertEquals(subField2.getType(), DataType.text());
110- }
111-
112- @Test(groups = "unit")
113- public void parseTupleTest() {
114- String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)";
115- TupleType type = (TupleType)CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
116- assertNotNull(type);
117- assertEquals(type.getComponentTypes().get(0), DataType.cint());
118- assertEquals(type.getComponentTypes().get(1), DataType.text());
119- assertEquals(type.getComponentTypes().get(2), DataType.cfloat());
120- }
121-
122- @Test(groups = "unit")
123- public void parseNestedCollectionTest() {
124- // map<text, frozen<map<int,int>>>
125- String s = "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))";
126-
127- DataType parentMap = CassandraTypeParser.parseOne(s, protocolVersion, codecRegistry);
128- assertThat(parentMap)
129- .hasName(DataType.Name.MAP)
130- .isNotFrozen()
131- .hasTypeArgument(0, DataType.text());
132-
133- DataType childMap = parentMap.getTypeArguments().get(1);
134- assertThat(childMap)
135- .hasName(DataType.Name.MAP)
136- .isFrozen()
137- .hasTypeArguments(DataType.cint(), DataType.cint());
138- }
139-}
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +16 −0
@@ -37,6 +37,14 @@
3737 return this;
3838 }
3939
40+ public DataTypeAssert isShallowUserType(String keyspaceName, String userTypeName) {
41+ assertThat(actual).isInstanceOf(UserType.Shallow.class);
42+ UserType.Shallow shallow = (UserType.Shallow)actual;
43+ assertThat(shallow.keyspaceName).isEqualTo(keyspaceName);
44+ assertThat(shallow.typeName).isEqualTo(userTypeName);
45+ return this;
46+ }
47+
4048 public DataTypeAssert isFrozen() {
4149 assertThat(actual.isFrozen()).isTrue();
4250 return this;
@@ -56,4 +64,12 @@
5664 assertThat(actual.getTypeArguments()).containsExactly(expected);
5765 return this;
5866 }
67+
68+ public DataTypeAssert hasField(String name, DataType expected) {
69+ assertThat(actual).isInstanceOf(UserType.class);
70+ UserType userType = (UserType)this.actual;
71+ assertThat(userType.getFieldType(name)).isEqualTo(expected);
72+ return this;
73+ }
74+
5975 }
added driver-core/src/test/java/com/datastax/driver/core/DataTypeClassNameParserTest.java +139 −0
@@ -0,0 +1,139 @@
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.Arrays;
19+import java.util.Iterator;
20+
21+import org.testng.annotations.Test;
22+
23+import static org.testng.Assert.assertEquals;
24+import static org.testng.Assert.assertFalse;
25+import static org.testng.Assert.assertNotNull;
26+import static org.testng.Assert.assertTrue;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+
30+public class DataTypeClassNameParserTest {
31+
32+ private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
33+ private CodecRegistry codecRegistry = new CodecRegistry();
34+
35+ @Test(groups = "unit")
36+ public void parseOneTest() {
37+
38+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.ByteType", protocolVersion, codecRegistry), DataType.tinyint());
39+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.ShortType", protocolVersion, codecRegistry), DataType.smallint());
40+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.SimpleDateType", protocolVersion, codecRegistry), DataType.date());
41+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.TimeType", protocolVersion, codecRegistry), DataType.time());
42+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.InetAddressType", protocolVersion, codecRegistry), DataType.inet());
43+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.list(DataType.text()));
44+ assertEquals(DataTypeClassNameParser.parseOne("org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", protocolVersion, codecRegistry), DataType.text());
45+
46+ String s;
47+
48+ s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type, org.apache.cassandra.db.marshal.Int32Type)";
49+ assertEquals(DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry), DataType.custom(s));
50+
51+ s = "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type))";
52+ assertEquals(DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry), DataType.list(DataType.cint()));
53+ }
54+
55+ @Test(groups = "unit")
56+ public void parseWithCompositeTest() {
57+
58+ String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,";
59+ s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))";
60+ DataTypeClassNameParser.ParseResult r1 = DataTypeClassNameParser.parseWithComposite(s, protocolVersion, codecRegistry);
61+ assertTrue(r1.isComposite);
62+ assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text()));
63+ assertEquals(r1.collections.size(), 1);
64+ assertEquals(r1.collections.get("ab"), DataType.list(DataType.cint()));
65+
66+ DataTypeClassNameParser.ParseResult r2 = DataTypeClassNameParser.parseWithComposite("org.apache.cassandra.db.marshal.TimestampType", protocolVersion, codecRegistry);
67+ assertFalse(r2.isComposite);
68+ assertEquals(r2.types, Arrays.asList(DataType.timestamp()));
69+ assertEquals(r2.collections.size(), 0);
70+ }
71+
72+ @Test(groups = "unit")
73+ public void parseUserTypes() {
74+
75+ String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))";
76+ UserType def = (UserType)DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
77+
78+ assertEquals(def.getKeyspace(), "foo");
79+ assertEquals(def.getTypeName(), "address");
80+
81+ Iterator<UserType.Field> iter = def.iterator();
82+
83+ UserType.Field field1 = iter.next();
84+ assertEquals(field1.getName(), "street");
85+ assertEquals(field1.getType(), DataType.text());
86+
87+ UserType.Field field2 = iter.next();
88+ assertEquals(field2.getName(), "zipcode");
89+ assertEquals(field2.getType(), DataType.cint());
90+
91+ UserType.Field field3 = iter.next();
92+ assertEquals(field3.getName(), "phones");
93+
94+ DataType st = field3.getType();
95+ assertEquals(st.getName(), DataType.Name.SET);
96+ UserType subDef = (UserType)st.getTypeArguments().get(0);
97+
98+ assertEquals(subDef.getKeyspace(), "foo");
99+ assertEquals(subDef.getTypeName(), "phone");
100+
101+ Iterator<UserType.Field> subIter = subDef.iterator();
102+
103+ UserType.Field subField1 = subIter.next();
104+ assertEquals(subField1.getName(), "name");
105+ assertEquals(subField1.getType(), DataType.text());
106+
107+ UserType.Field subField2 = subIter.next();
108+ assertEquals(subField2.getName(), "number");
109+ assertEquals(subField2.getType(), DataType.text());
110+ }
111+
112+ @Test(groups = "unit")
113+ public void parseTupleTest() {
114+ String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)";
115+ TupleType type = (TupleType)DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
116+ assertNotNull(type);
117+ assertEquals(type.getComponentTypes().get(0), DataType.cint());
118+ assertEquals(type.getComponentTypes().get(1), DataType.text());
119+ assertEquals(type.getComponentTypes().get(2), DataType.cfloat());
120+ }
121+
122+ @Test(groups = "unit")
123+ public void parseNestedCollectionTest() {
124+ // map<text, frozen<map<int,int>>>
125+ String s = "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))";
126+
127+ DataType parentMap = DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
128+ assertThat(parentMap)
129+ .hasName(DataType.Name.MAP)
130+ .isNotFrozen()
131+ .hasTypeArgument(0, DataType.text());
132+
133+ DataType childMap = parentMap.getTypeArguments().get(1);
134+ assertThat(childMap)
135+ .hasName(DataType.Name.MAP)
136+ .isFrozen()
137+ .hasTypeArguments(DataType.cint(), DataType.cint());
138+ }
139+}
added driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java +129 −0
@@ -0,0 +1,129 @@
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+
20+import com.google.common.collect.Lists;
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.DataTypeCqlNameParser.parse;
28+
29+@CassandraVersion(major = 3.0)
30+public class DataTypeCqlNameParserTest extends CCMBridge.PerClassSingleNodeCluster {
31+
32+ @Test(groups = "short")
33+ public void should_parse_native_types() {
34+ assertThat(parse("ascii", cluster, null, null, null, false, false)).isEqualTo(ascii());
35+ assertThat(parse("bigint", cluster, null, null, null, false, false)).isEqualTo(bigint());
36+ assertThat(parse("blob", cluster, null, null, null, false, false)).isEqualTo(blob());
37+ assertThat(parse("boolean", cluster, null, null, null, false, false)).isEqualTo(cboolean());
38+ assertThat(parse("counter", cluster, null, null, null, false, false)).isEqualTo(counter());
39+ assertThat(parse("decimal", cluster, null, null, null, false, false)).isEqualTo(decimal());
40+ assertThat(parse("double", cluster, null, null, null, false, false)).isEqualTo(cdouble());
41+ assertThat(parse("float", cluster, null, null, null, false, false)).isEqualTo(cfloat());
42+ assertThat(parse("inet", cluster, null, null, null, false, false)).isEqualTo(inet());
43+ assertThat(parse("int", cluster, null, null, null, false, false)).isEqualTo(cint());
44+ assertThat(parse("text", cluster, null, null, null, false, false)).isEqualTo(text());
45+ assertThat(parse("varchar", cluster, null, null, null, false, false)).isEqualTo(varchar());
46+ assertThat(parse("timestamp", cluster, null, null, null, false, false)).isEqualTo(timestamp());
47+ assertThat(parse("date", cluster, null, null, null, false, false)).isEqualTo(date());
48+ assertThat(parse("time", cluster, null, null, null, false, false)).isEqualTo(time());
49+ assertThat(parse("uuid", cluster, null, null, null, false, false)).isEqualTo(uuid());
50+ assertThat(parse("varint", cluster, null, null, null, false, false)).isEqualTo(varint());
51+ assertThat(parse("timeuuid", cluster, null, null, null, false, false)).isEqualTo(timeuuid());
52+ assertThat(parse("tinyint", cluster, null, null, null, false, false)).isEqualTo(tinyint());
53+ assertThat(parse("smallint", cluster, null, null, null, false, false)).isEqualTo(smallint());
54+ }
55+
56+ @Test(groups = "short")
57+ public void should_ignore_whitespace() {
58+ assertThat(parse(" int ", cluster, null, null, null, false, false)).isEqualTo(cint());
59+ assertThat(parse(" set < bigint > ", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
60+ assertThat(parse(" map < date , timeuuid > ", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
61+ }
62+
63+ @Test(groups = "short")
64+ public void should_ignore_case() {
65+ assertThat(parse("INT", cluster, null, null, null, false, false)).isEqualTo(cint());
66+ assertThat(parse("SET<BIGint>", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
67+ assertThat(parse("FROZEN<mAp<Date,Tuple<timeUUID>>>", cluster, null, null, null, false, false)).isEqualTo(map(date(), cluster.getMetadata().newTupleType(timeuuid()), true));
68+ }
69+
70+ @Test(groups = "short")
71+ public void should_parse_collection_types() {
72+ assertThat(parse("list<int>", cluster, null, null, null, false, false)).isEqualTo(list(cint()));
73+ assertThat(parse("set<bigint>", cluster, null, null, null, false, false)).isEqualTo(set(bigint()));
74+ assertThat(parse("map<date,timeuuid>", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid()));
75+ }
76+
77+ @Test(groups = "short")
78+ public void should_parse_frozen_collection_types() {
79+ assertThat(parse("frozen<list<int>>", cluster, null, null, null, false, false)).isEqualTo(list(cint(), true));
80+ assertThat(parse("frozen<set<bigint>>", cluster, null, null, null, false, false)).isEqualTo(set(bigint(), true));
81+ assertThat(parse("frozen<map<date,timeuuid>>", cluster, null, null, null, false, false)).isEqualTo(map(date(), timeuuid(), true));
82+ }
83+
84+ @Test(groups = "short")
85+ public void should_parse_nested_collection_types() {
86+ Metadata metadata = cluster.getMetadata();
87+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
88+ assertThat(parse("list<list<int>>", cluster, null, null, null, false, false)).isEqualTo(list(list(cint())));
89+ assertThat(parse("set<list<frozen<map<bigint,varchar>>>>", cluster, null, null, null, false, false)).isEqualTo(set(list(map(bigint(), varchar(), true))));
90+
91+ UserType keyType = keyspaceMetadata.getUserType("Incr,edibly\" EvilTy<>><<><p\"e");
92+ UserType valueType = keyspaceMetadata.getUserType("\"A\"");
93+ assertThat(parse("map<frozen<\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\">,frozen<\"A\">>", cluster, keyspace, keyspaceMetadata.userTypes, null, false, false))
94+ .isEqualTo(map(keyType, valueType, false));
95+ }
96+
97+ @Test(groups = "short")
98+ public void should_parse_tuple_types() {
99+ assertThat(parse("tuple<int,list<text>>", cluster, null, null, null, false, false)).isEqualTo(cluster.getMetadata().newTupleType(cint(), list(text())));
100+ }
101+
102+ @Test(groups = "short")
103+ public void should_parse_user_defined_type_when_definition_in_current_user_types() {
104+ Metadata metadata = cluster.getMetadata();
105+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
106+ assertThat(parse("frozen<\"A\">", cluster, keyspace, keyspaceMetadata.userTypes, null, false, false)).isUserType(keyspace, "A");
107+ }
108+
109+ @Test(groups = "short")
110+ public void should_parse_user_defined_type_when_definition_in_old_user_types() {
111+ Metadata metadata = cluster.getMetadata();
112+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(this.keyspace);
113+ assertThat(parse("\"A\"", cluster, keyspace, null, keyspaceMetadata.userTypes, false, false)).isUserType(keyspace, "A");
114+ }
115+
116+ @Test(groups = "short")
117+ public void should_parse_user_defined_type_to_shallow_type_if_requested() {
118+ assertThat(parse("\"A\"", cluster, keyspace, null, null, false, true)).isShallowUserType(keyspace, "A");
119+ }
120+
121+ @Override
122+ protected Collection<String> getTableDefinitions() {
123+ return Lists.newArrayList(
124+ String.format("CREATE TYPE %s.\"A\" (f1 int)", keyspace),
125+ String.format("CREATE TYPE %s.\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\" (a frozen<\"A\">)", keyspace)
126+ );
127+ }
128+
129+}
added driver-core/src/test/java/com/datastax/driver/core/DirectedGraphTest.java +96 −0
@@ -0,0 +1,96 @@
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.List;
19+
20+import org.testng.annotations.Test;
21+
22+import static org.assertj.core.api.Assertions.assertThat;
23+
24+import com.datastax.driver.core.exceptions.DriverInternalError;
25+
26+public class DirectedGraphTest {
27+ @Test(groups = "unit")
28+ public void should_sort_empty_graph() {
29+ DirectedGraph<String> g = new DirectedGraph<String>();
30+ assertThat(g.topologicalSort()).isEmpty();
31+ }
32+
33+ @Test(groups = "unit")
34+ public void should_sort_graph_with_one_node() {
35+ DirectedGraph<String> g = new DirectedGraph<String>("A");
36+ assertThat(g.topologicalSort())
37+ .containsExactly("A");
38+ }
39+
40+ @Test(groups = "unit")
41+ public void should_sort_complex_graph() {
42+ // H G
43+ // / \ /\
44+ // F | E
45+ // \ / /
46+ // D /
47+ // / \/
48+ // B C
49+ // |
50+ // A
51+ DirectedGraph<String> g = new DirectedGraph<String>("A", "B", "C", "D", "E", "F", "G", "H");
52+ g.addEdge("H", "F");
53+ g.addEdge("G", "E");
54+ g.addEdge("H", "D");
55+ g.addEdge("F", "D");
56+ g.addEdge("G", "D");
57+ g.addEdge("D", "C");
58+ g.addEdge("E", "C");
59+ g.addEdge("D", "B");
60+ g.addEdge("B", "A");
61+
62+ // Topological sort order should be : GH,FE,D,CB,A
63+ // There's no guarantee on the order within the same level, so we use sublists:
64+ List<String> sorted = g.topologicalSort();
65+ assertThat(sorted.subList(0, 2))
66+ .contains("G", "H");
67+ assertThat(sorted.subList(2, 4))
68+ .contains("F", "E");
69+ assertThat(sorted.subList(4, 5))
70+ .contains("D");
71+ assertThat(sorted.subList(5, 7))
72+ .contains("C", "B" );
73+ assertThat(sorted.subList(7, 8))
74+ .contains("A");
75+ }
76+
77+ @Test(groups = "unit", expectedExceptions = DriverInternalError.class)
78+ public void should_fail_to_sort_if_graph_has_a_cycle() {
79+ DirectedGraph<String> g = new DirectedGraph<String>("A", "B", "C");
80+ g.addEdge("A", "B");
81+ g.addEdge("B", "C");
82+ g.addEdge("C", "B");
83+
84+ g.topologicalSort();
85+ }
86+
87+ @Test(groups = "unit", expectedExceptions = DriverInternalError.class)
88+ public void should_fail_to_sort_if_graph_is_a_cycle() {
89+ DirectedGraph<String> g = new DirectedGraph<String>("A", "B", "C");
90+ g.addEdge("A", "B");
91+ g.addEdge("B", "C");
92+ g.addEdge("C", "A");
93+
94+ g.topologicalSort();
95+ }
96+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +34 −62
@@ -15,63 +15,60 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.Collection;
1819 import java.util.Collections;
19-import java.util.List;
2020
21-import com.google.common.collect.ImmutableList;
22-import org.testng.annotations.BeforeMethod;
2321 import org.testng.annotations.Test;
2422
25-import static org.mockito.Mockito.mock;
26-import static org.mockito.Mockito.when;
23+import com.datastax.driver.core.utils.CassandraVersion;
2724
2825 import static com.datastax.driver.core.Assertions.assertThat;
26+import static com.datastax.driver.core.DataType.cint;
2927
30-public class FunctionMetadataTest {
31- KeyspaceMetadata keyspace;
32- private ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
33- private CodecRegistry codecRegistry = new CodecRegistry();
34-
35- @BeforeMethod(groups = "unit")
36- public void setup() {
37- keyspace = new KeyspaceMetadata("ks", false, Collections.<String, String>emptyMap());
38- }
28+@CassandraVersion(major = 2.2)
29+public class FunctionMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3930
40- @Test(groups = "unit")
31+ @Test(groups = "short")
4132 public void should_parse_and_format_simple_function() {
42- FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PLUS, protocolVersion, codecRegistry);
43-
33+ // given
34+ String cql = String.format("CREATE FUNCTION %s.plus(s int,v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return s+v;';", keyspace);
35+ // when
36+ session.execute(cql);
37+ // then
38+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
39+ FunctionMetadata function = keyspace.getFunction("plus", cint(), cint());
4440 assertThat(function).isNotNull();
4541 assertThat(function.getKeyspace()).isEqualTo(keyspace);
4642 assertThat(function.getFullName()).isEqualTo("plus(int,int)");
4743 assertThat(function.getSimpleName()).isEqualTo("plus");
48- assertThat(function.getReturnType()).isEqualTo(DataType.cint());
44+ assertThat(function.getReturnType()).isEqualTo(cint());
4945 assertThat(function.getArguments())
50- .containsEntry("s", DataType.cint())
51- .containsEntry("v", DataType.cint());
46+ .containsEntry("s", cint())
47+ .containsEntry("v", cint());
5248 assertThat(function.getLanguage()).isEqualTo("java");
5349 assertThat(function.getBody()).isEqualTo("return s+v;");
5450 assertThat(function.isCalledOnNullInput()).isFalse();
55-
56- assertThat(keyspace.getFunction("plus", DataType.cint(), DataType.cint())).isEqualTo(function);
57-
5851 assertThat(function.toString())
59- .isEqualTo("CREATE FUNCTION ks.plus(s int,v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return s+v;';");
60-
52+ .isEqualTo(cql);
6153 assertThat(function.exportAsString())
62- .isEqualTo("CREATE FUNCTION ks.plus(\n"
54+ .isEqualTo(String.format("CREATE FUNCTION %s.plus(\n"
6355 + " s int,\n"
6456 + " v int)\n"
6557 + "RETURNS NULL ON NULL INPUT\n"
6658 + "RETURNS int\n"
6759 + "LANGUAGE java\n"
68- + "AS 'return s+v;';");
60+ + "AS 'return s+v;';", this.keyspace));
6961 }
7062
71- @Test(groups = "unit")
63+ @Test(groups = "short")
7264 public void should_parse_and_format_function_with_no_arguments() {
73- FunctionMetadata function = FunctionMetadata.build(keyspace, SYSTEM_ROW_PI, protocolVersion, codecRegistry);
74-
65+ // given
66+ String cql = String.format("CREATE FUNCTION %s.pi() CALLED ON NULL INPUT RETURNS double LANGUAGE java AS 'return Math.PI;';", keyspace);
67+ // when
68+ session.execute(cql);
69+ // then
70+ KeyspaceMetadata keyspace = cluster.getMetadata().getKeyspace(this.keyspace);
71+ FunctionMetadata function = keyspace.getFunction("pi");
7572 assertThat(function).isNotNull();
7673 assertThat(function.getKeyspace()).isEqualTo(keyspace);
7774 assertThat(function.getFullName()).isEqualTo("pi()");
@@ -81,45 +78,20 @@
8178 assertThat(function.getLanguage()).isEqualTo("java");
8279 assertThat(function.getBody()).isEqualTo("return Math.PI;");
8380 assertThat(function.isCalledOnNullInput()).isTrue();
84-
8581 assertThat(keyspace.getFunction("pi")).isEqualTo(function);
86-
8782 assertThat(function.toString())
88- .isEqualTo("CREATE FUNCTION ks.pi() CALLED ON NULL INPUT RETURNS double LANGUAGE java AS 'return Math.PI;';");
89-
83+ .isEqualTo(cql);
9084 assertThat(function.exportAsString())
91- .isEqualTo("CREATE FUNCTION ks.pi()\n"
85+ .isEqualTo(String.format("CREATE FUNCTION %s.pi()\n"
9286 + "CALLED ON NULL INPUT\n"
9387 + "RETURNS double\n"
9488 + "LANGUAGE java\n"
95- + "AS 'return Math.PI;';");
89+ + "AS 'return Math.PI;';", this.keyspace));
9690 }
9791
98- private static final String INT = "org.apache.cassandra.db.marshal.Int32Type";
99- private static final String DOUBLE = "org.apache.cassandra.db.marshal.DoubleType";
100-
101- private static final Row SYSTEM_ROW_PLUS = mockRow("plus",
102- ImmutableList.of("int", "int"), ImmutableList.of("s", "v"), ImmutableList.of(INT, INT),
103- "return s+v;", false, "java", INT
104- );
105-
106- private static final Row SYSTEM_ROW_PI = mockRow("pi",
107- Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
108- "return Math.PI;", true, "java", DOUBLE);
109-
110- private static Row mockRow(String functionName, List<String> signature, List<String> argumentNames, List<String> argumentTypes,
111- String body, boolean calledOnNullInput, String language, String returnType) {
112- Row row = mock(Row.class);
113-
114- when(row.getString("function_name")).thenReturn(functionName);
115- when(row.getList("signature", String.class)).thenReturn(signature);
116- when(row.getList("argument_names", String.class)).thenReturn(argumentNames);
117- when(row.getList("argument_types", String.class)).thenReturn(argumentTypes);
118- when(row.getString("body")).thenReturn(body);
119- when(row.getBool("called_on_null_input")).thenReturn(calledOnNullInput);
120- when(row.getString("language")).thenReturn(language);
121- when(row.getString("return_type")).thenReturn(returnType);
122-
123- return row;
92+ @Override
93+ protected Collection<String> getTableDefinitions() {
94+ return Collections.emptyList();
12495 }
96+
12597 }
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +11 −12
@@ -61,18 +61,19 @@
6161 definition(IndexMetadata.KIND, text()),
6262 definition(IndexMetadata.OPTIONS, map(text(), text()))
6363 });
64- public static final TypeCodec<Map<String, String>> MAP_CODEC = TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar());
65-
66- private static ProtocolVersion protocolVersion;
67- private static CodecRegistry codecRegistry;
64+
65+ private static final TypeCodec<Map<String, String>> MAP_CODEC = TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar());
66+
67+ private ProtocolVersion protocolVersion;
6868
69+ @Override
6970 @BeforeClass(groups = { "short", "long" })
7071 public void beforeClass() {
7172 super.beforeClass();
72- protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
73- codecRegistry = cluster.getConfiguration().getCodecRegistry();
73+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
7474 legacyColumnDefs.setCodecRegistry(codecRegistry);
7575 indexColumnDefs.setCodecRegistry(codecRegistry);
76+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
7677 }
7778
7879 @Override
@@ -285,8 +286,8 @@
285286 wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
286287 );
287288 Row columnRow = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, protocolVersion, columnData);
288- Raw columnRaw = Raw.fromRow(columnRow, VersionNumber.parse("2.1"), protocolVersion, codecRegistry);
289- ColumnMetadata column = ColumnMetadata.fromRaw(table, columnRaw);
289+ Raw columnRaw = Raw.fromRow(columnRow, VersionNumber.parse("2.1"));
290+ ColumnMetadata column = ColumnMetadata.fromRaw(table, columnRaw, DataType.varchar());
290291 IndexMetadata index = IndexMetadata.fromLegacy(column, columnRaw);
291292 assertThat(index)
292293 .isNotNull()
@@ -348,10 +349,8 @@
348349 wrap("null") // index options
349350 );
350351 Row row = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), data);
351- Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"),
352- cluster.getConfiguration().getProtocolOptions().getProtocolVersion(),
353- cluster.getConfiguration().getCodecRegistry());
354- ColumnMetadata column = ColumnMetadata.fromRaw(table, raw);
352+ Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"));
353+ ColumnMetadata column = ColumnMetadata.fromRaw(table, raw, DataType.blob());
355354 IndexMetadata index = IndexMetadata.fromLegacy(column, raw);
356355 assertThat(index)
357356 .isNotNull()
added driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java +106 −0
@@ -0,0 +1,106 @@
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+import java.util.concurrent.ExecutionException;
21+
22+import com.google.common.collect.Lists;
23+import org.testng.annotations.Test;
24+
25+import com.datastax.driver.core.utils.CassandraVersion;
26+
27+import static com.datastax.driver.core.Assertions.assertThat;
28+import static com.datastax.driver.core.DataType.cint;
29+import static com.datastax.driver.core.DataType.list;
30+import static com.datastax.driver.core.DataType.map;
31+import static com.datastax.driver.core.DataType.set;
32+
33+@CassandraVersion(major = 3.0)
34+public class UnresolvedUserTypeTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return Lists.newArrayList(
39+ /*
40+ Creates the following acyclic graph (edges directed upwards
41+ meaning "depends on"):
42+
43+ H G
44+ / \ /\
45+ F | E
46+ \ / /
47+ D /
48+ / \/
49+ B C
50+ |
51+ A
52+
53+ Topological sort order should be : GH,FE,D,CB,A
54+ */
55+ String.format("CREATE TYPE %s.h (f1 int)", keyspace),
56+ String.format("CREATE TYPE %s.g (f1 int)", keyspace),
57+ String.format("CREATE TYPE %s.\"F\" (f1 frozen<h>)", keyspace),
58+ String.format("CREATE TYPE %s.\"E\" (f1 frozen<list<g>>)", keyspace),
59+ String.format("CREATE TYPE %s.\"D\" (f1 frozen<tuple<\"F\",g,h>>)", keyspace),
60+ String.format("CREATE TYPE %s.\"C\" (f1 frozen<map<\"E\",\"D\">>)", keyspace),
61+ String.format("CREATE TYPE %s.\"B\" (f1 frozen<set<\"D\">>)", keyspace),
62+ String.format("CREATE TYPE %s.\"A\" (f1 frozen<\"C\">)", keyspace)
63+ );
64+ }
65+
66+ @Test(groups = "short")
67+ public void should_resolve_nested_user_types() throws ExecutionException, InterruptedException {
68+
69+ // Each CREATE TYPE statement in getTableDefinitions() has triggered a partial schema refresh that
70+ // should have used previous UDT definitions for dependencies.
71+ checkUserTypes(cluster.getMetadata());
72+
73+ // Create a different Cluster instance to force a full refresh where all UDTs are loaded at once.
74+ // The parsing logic should sort them to make sure they are loaded in the right order.
75+ Cluster newCluster = null;
76+ try {
77+ newCluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
78+ checkUserTypes(newCluster.getMetadata());
79+ } finally {
80+ if (newCluster != null)
81+ newCluster.close();
82+ }
83+ }
84+
85+ private void checkUserTypes(Metadata metadata) {
86+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
87+
88+ UserType a = keyspaceMetadata.getUserType("\"A\"");
89+ UserType b = keyspaceMetadata.getUserType("\"B\"");
90+ UserType c = keyspaceMetadata.getUserType("\"C\"");
91+ UserType d = keyspaceMetadata.getUserType("\"D\"");
92+ UserType e = keyspaceMetadata.getUserType("\"E\"");
93+ UserType f = keyspaceMetadata.getUserType("\"F\"");
94+ UserType g = keyspaceMetadata.getUserType("g");
95+ UserType h = keyspaceMetadata.getUserType("h");
96+
97+ assertThat(a).hasField("f1", c);
98+ assertThat(b).hasField("f1", set(d));
99+ assertThat(c).hasField("f1", map(e, d));
100+ assertThat(d).hasField("f1", metadata.newTupleType(f, g, h));
101+ assertThat(e).hasField("f1", list(g));
102+ assertThat(f).hasField("f1", h);
103+ assertThat(g).hasField("f1", cint());
104+ assertThat(h).hasField("f1", cint());
105+ }
106+}
modified pom.xml +1 −1
@@ -43,7 +43,7 @@
4343
4444 <properties>
4545 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
46- <cassandra.version>3.0.0-rc1</cassandra.version>
46+ <cassandra.version>3.0.0</cassandra.version>
4747 <java.version>1.6</java.version>
4848 <log4j.version>1.2.17</log4j.version>
4949 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>