kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 4d9e392bb521422491c63e0d8ca1080144e2e1cf48006f76301d65a307659d44 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-03-06 17:00 -08:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-03-06 17:23 -08:00 |
| Parents | 5cc80eb128f8 |
39 files changed
modified driver-core/CHANGELOG.rst +4 −0
| @@ -4,7 +4,11 @@ | ||
| 4 | 4 | 2.1.5: |
| 5 | 5 | ------ |
| 6 | 6 | |
| 7 | +- [bug] Fix checks on mapped collection types (JAVA-612) | |
| 7 | 8 | - [bug] Authorize Null parameter in Accessor method (JAVA-575) |
| 9 | +- [improvement] Support C* 2.1.3's nested collections (JAVA-570) | |
| 10 | +- [bug] Fix checks on mapped collection types (JAVA-612) | |
| 11 | +- [bug] Fix QueryBuilder.putAll() when the collection contains UDTs (JAVA-672) | |
| 8 | 12 | |
| 9 | 13 | Merged from 2.0 branch: |
| 10 | 14 |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +69 −3
| @@ -26,6 +26,8 @@ | ||
| 26 | 26 | import java.util.Set; |
| 27 | 27 | import java.util.UUID; |
| 28 | 28 | |
| 29 | +import com.google.common.reflect.TypeToken; | |
| 30 | + | |
| 29 | 31 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 30 | 32 | |
| 31 | 33 | abstract class AbstractGettableByIndexData implements GettableByIndexData { |
| @@ -290,7 +292,28 @@ | ||
| 290 | 292 | |
| 291 | 293 | Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType; |
| 292 | 294 | if (!elementsClass.isAssignableFrom(expectedClass)) |
| 293 | - throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieve as a list of %s", getName(i), expectedClass, type, elementsClass)); | |
| 295 | + throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieved as a list of %s", getName(i), expectedClass, type, elementsClass)); | |
| 296 | + | |
| 297 | + ByteBuffer value = getValue(i); | |
| 298 | + if (value == null) | |
| 299 | + return Collections.<T>emptyList(); | |
| 300 | + | |
| 301 | + return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value)); | |
| 302 | + } | |
| 303 | + | |
| 304 | + /** | |
| 305 | + * {@inheritDoc} | |
| 306 | + */ | |
| 307 | + @Override | |
| 308 | + @SuppressWarnings("unchecked") | |
| 309 | + public <T> List<T> getList(int i, TypeToken<T> elementsType) { | |
| 310 | + DataType type = getType(i); | |
| 311 | + if (type.getName() != DataType.Name.LIST) | |
| 312 | + throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i))); | |
| 313 | + | |
| 314 | + DataType expectedType = type.getTypeArguments().get(0); | |
| 315 | + if (!expectedType.canBeDeserializedAs(elementsType)) | |
| 316 | + throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a list of %s", getName(i), type, elementsType)); | |
| 294 | 317 | |
| 295 | 318 | ByteBuffer value = getValue(i); |
| 296 | 319 | if (value == null) |
| @@ -311,7 +334,28 @@ | ||
| 311 | 334 | |
| 312 | 335 | Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType; |
| 313 | 336 | if (!elementsClass.isAssignableFrom(expectedClass)) |
| 314 | - throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieve as a set of %s", getName(i), expectedClass, type, elementsClass)); | |
| 337 | + throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieved as a set of %s", getName(i), expectedClass, type, elementsClass)); | |
| 338 | + | |
| 339 | + ByteBuffer value = getValue(i); | |
| 340 | + if (value == null) | |
| 341 | + return Collections.<T>emptySet(); | |
| 342 | + | |
| 343 | + return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value)); | |
| 344 | + } | |
| 345 | + | |
| 346 | + /** | |
| 347 | + * {@inheritDoc} | |
| 348 | + */ | |
| 349 | + @Override | |
| 350 | + @SuppressWarnings("unchecked") | |
| 351 | + public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { | |
| 352 | + DataType type = getType(i); | |
| 353 | + if (type.getName() != DataType.Name.SET) | |
| 354 | + throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i))); | |
| 355 | + | |
| 356 | + DataType expectedType = type.getTypeArguments().get(0); | |
| 357 | + if (!expectedType.canBeDeserializedAs(elementsType)) | |
| 358 | + throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a set of %s", getName(i), type, elementsType)); | |
| 315 | 359 | |
| 316 | 360 | ByteBuffer value = getValue(i); |
| 317 | 361 | if (value == null) |
| @@ -333,7 +377,29 @@ | ||
| 333 | 377 | Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType; |
| 334 | 378 | Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType; |
| 335 | 379 | if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass)) |
| 336 | - throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass)); | |
| 380 | + throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieved as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass)); | |
| 381 | + | |
| 382 | + ByteBuffer value = getValue(i); | |
| 383 | + if (value == null) | |
| 384 | + return Collections.<K, V>emptyMap(); | |
| 385 | + | |
| 386 | + return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value)); | |
| 387 | + } | |
| 388 | + | |
| 389 | + /** | |
| 390 | + * {@inheritDoc} | |
| 391 | + */ | |
| 392 | + @Override | |
| 393 | + @SuppressWarnings("unchecked") | |
| 394 | + public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { | |
| 395 | + DataType type = getType(i); | |
| 396 | + if (type.getName() != DataType.Name.MAP) | |
| 397 | + throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i))); | |
| 398 | + | |
| 399 | + DataType expectedKeysType = type.getTypeArguments().get(0); | |
| 400 | + DataType expectedValuesType = type.getTypeArguments().get(1); | |
| 401 | + if (!expectedKeysType.canBeDeserializedAs(keysType) || !expectedValuesType.canBeDeserializedAs(valuesType)) | |
| 402 | + throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a map of %s->%s", getName(i), type, keysType, valuesType)); | |
| 337 | 403 | |
| 338 | 404 | ByteBuffer value = getValue(i); |
| 339 | 405 | if (value == null) |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +26 −0
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | public abstract class AbstractGettableData extends AbstractGettableByIndexData implements GettableData { |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -177,6 +179,14 @@ | ||
| 177 | 179 | return getList(getIndexOf(name), elementsClass); |
| 178 | 180 | } |
| 179 | 181 | |
| 182 | + /** | |
| 183 | + * {@inheritDoc} | |
| 184 | + */ | |
| 185 | + @Override | |
| 186 | + public <T> List<T> getList(String name, TypeToken<T> elementsType) { | |
| 187 | + return getList(getIndexOf(name), elementsType); | |
| 188 | + } | |
| 189 | + | |
| 180 | 190 | /** |
| 181 | 191 | * {@inheritDoc} |
| 182 | 192 | */ |
| @@ -185,6 +195,14 @@ | ||
| 185 | 195 | return getSet(getIndexOf(name), elementsClass); |
| 186 | 196 | } |
| 187 | 197 | |
| 198 | + /** | |
| 199 | + * {@inheritDoc} | |
| 200 | + */ | |
| 201 | + @Override | |
| 202 | + public <T> Set<T> getSet(String name, TypeToken<T> elementsType) { | |
| 203 | + return getSet(getIndexOf(name), elementsType); | |
| 204 | + } | |
| 205 | + | |
| 188 | 206 | /** |
| 189 | 207 | * {@inheritDoc} |
| 190 | 208 | */ |
| @@ -193,6 +211,14 @@ | ||
| 193 | 211 | return getMap(getIndexOf(name), keysClass, valuesClass); |
| 194 | 212 | } |
| 195 | 213 | |
| 214 | + /** | |
| 215 | + * {@inheritDoc} | |
| 216 | + */ | |
| 217 | + @Override | |
| 218 | + public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) { | |
| 219 | + return getMap(getIndexOf(name), keysType, valuesType); | |
| 220 | + } | |
| 221 | + | |
| 196 | 222 | /** |
| 197 | 223 | * {@inheritDoc} |
| 198 | 224 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +44 −0
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -1238,6 +1240,13 @@ | ||
| 1238 | 1240 | return wrapper.getList(i, elementsClass); |
| 1239 | 1241 | } |
| 1240 | 1242 | |
| 1243 | + /** | |
| 1244 | + * {@inheritDoc} | |
| 1245 | + */ | |
| 1246 | + public <T> List<T> getList(int i, TypeToken<T> elementsType) { | |
| 1247 | + return wrapper.getList(i, elementsType); | |
| 1248 | + } | |
| 1249 | + | |
| 1241 | 1250 | /** |
| 1242 | 1251 | * {@inheritDoc} |
| 1243 | 1252 | */ |
| @@ -1245,6 +1254,13 @@ | ||
| 1245 | 1254 | return wrapper.getList(name, elementsClass); |
| 1246 | 1255 | } |
| 1247 | 1256 | |
| 1257 | + /** | |
| 1258 | + * {@inheritDoc} | |
| 1259 | + */ | |
| 1260 | + public <T> List<T> getList(String name, TypeToken<T> elementsType) { | |
| 1261 | + return wrapper.getList(name, elementsType); | |
| 1262 | + } | |
| 1263 | + | |
| 1248 | 1264 | /** |
| 1249 | 1265 | * {@inheritDoc} |
| 1250 | 1266 | */ |
| @@ -1252,6 +1268,13 @@ | ||
| 1252 | 1268 | return wrapper.getSet(i, elementsClass); |
| 1253 | 1269 | } |
| 1254 | 1270 | |
| 1271 | + /** | |
| 1272 | + * {@inheritDoc} | |
| 1273 | + */ | |
| 1274 | + public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { | |
| 1275 | + return wrapper.getSet(i, elementsType); | |
| 1276 | + } | |
| 1277 | + | |
| 1255 | 1278 | /** |
| 1256 | 1279 | * {@inheritDoc} |
| 1257 | 1280 | */ |
| @@ -1259,6 +1282,13 @@ | ||
| 1259 | 1282 | return wrapper.getSet(name, elementsClass); |
| 1260 | 1283 | } |
| 1261 | 1284 | |
| 1285 | + /** | |
| 1286 | + * {@inheritDoc} | |
| 1287 | + */ | |
| 1288 | + public <T> Set<T> getSet(String name, TypeToken<T> elementsType) { | |
| 1289 | + return wrapper.getSet(name, elementsType); | |
| 1290 | + } | |
| 1291 | + | |
| 1262 | 1292 | /** |
| 1263 | 1293 | * {@inheritDoc} |
| 1264 | 1294 | */ |
| @@ -1266,6 +1296,13 @@ | ||
| 1266 | 1296 | return wrapper.getMap(i, keysClass, valuesClass); |
| 1267 | 1297 | } |
| 1268 | 1298 | |
| 1299 | + /** | |
| 1300 | + * {@inheritDoc} | |
| 1301 | + */ | |
| 1302 | + public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { | |
| 1303 | + return wrapper.getMap(i, keysType, valuesType); | |
| 1304 | + } | |
| 1305 | + | |
| 1269 | 1306 | /** |
| 1270 | 1307 | * {@inheritDoc} |
| 1271 | 1308 | */ |
| @@ -1273,6 +1310,13 @@ | ||
| 1273 | 1310 | return wrapper.getMap(name, keysClass, valuesClass); |
| 1274 | 1311 | } |
| 1275 | 1312 | |
| 1313 | + /** | |
| 1314 | + * {@inheritDoc} | |
| 1315 | + */ | |
| 1316 | + public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) { | |
| 1317 | + return wrapper.getMap(name, keysType, valuesType); | |
| 1318 | + } | |
| 1319 | + | |
| 1276 | 1320 | /** |
| 1277 | 1321 | * {@inheritDoc} |
| 1278 | 1322 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/CassandraTypeParser.java +30 −9
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | 20 | import com.google.common.collect.ImmutableMap; |
| 21 | +import org.slf4j.Logger; | |
| 22 | +import org.slf4j.LoggerFactory; | |
| 21 | 23 | |
| 22 | 24 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 23 | 25 | import com.datastax.driver.core.utils.Bytes; |
| @@ -35,8 +37,10 @@ | ||
| 35 | 37 | * so there shouldn't be anything wrong with them. |
| 36 | 38 | */ |
| 37 | 39 | class CassandraTypeParser { |
| 40 | + private static final Logger logger = LoggerFactory.getLogger(CassandraTypeParser.class); | |
| 38 | 41 | |
| 39 | 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"; | |
| 40 | 44 | private static final String COMPOSITE_TYPE = "org.apache.cassandra.db.marshal.CompositeType"; |
| 41 | 45 | private static final String COLLECTION_TYPE = "org.apache.cassandra.db.marshal.ColumnToCollectionType"; |
| 42 | 46 | private static final String LIST_TYPE = "org.apache.cassandra.db.marshal.ListType"; |
| @@ -66,30 +70,33 @@ | ||
| 66 | 70 | .build(); |
| 67 | 71 | |
| 68 | 72 | static DataType parseOne(String className) { |
| 73 | + boolean frozen = false; | |
| 69 | 74 | if (isReversed(className)) { |
| 70 | 75 | // Just skip the ReversedType part, we don't care |
| 71 | - Parser p = new Parser(className, 0); | |
| 72 | - p.parseNextName(); | |
| 73 | - List<String> l = p.getTypeParameters(); | |
| 74 | - if (l.size() != 1) | |
| 75 | - throw new IllegalStateException(); | |
| 76 | - className = l.get(0); | |
| 76 | + className = getNestedClassName(className); | |
| 77 | + } else if (isFrozen(className)) { | |
| 78 | + frozen = true; | |
| 79 | + className = getNestedClassName(className); | |
| 77 | 80 | } |
| 78 | 81 | |
| 79 | 82 | Parser parser = new Parser(className, 0); |
| 80 | 83 | String next = parser.parseNextName(); |
| 81 | 84 | |
| 82 | 85 | if (next.startsWith(LIST_TYPE)) |
| 83 | - return DataType.list(parseOne(parser.getTypeParameters().get(0))); | |
| 86 | + return DataType.list(parseOne(parser.getTypeParameters().get(0)), frozen); | |
| 84 | 87 | |
| 85 | 88 | if (next.startsWith(SET_TYPE)) |
| 86 | - return DataType.set(parseOne(parser.getTypeParameters().get(0))); | |
| 89 | + return DataType.set(parseOne(parser.getTypeParameters().get(0)), frozen); | |
| 87 | 90 | |
| 88 | 91 | if (next.startsWith(MAP_TYPE)) { |
| 89 | 92 | List<String> params = parser.getTypeParameters(); |
| 90 | - return DataType.map(parseOne(params.get(0)), parseOne(params.get(1))); | |
| 93 | + return DataType.map(parseOne(params.get(0)), parseOne(params.get(1)), frozen); | |
| 91 | 94 | } |
| 92 | 95 | |
| 96 | + if (frozen) | |
| 97 | + logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, " | |
| 98 | + + "this driver version might be too old for your version of Cassandra"); | |
| 99 | + | |
| 93 | 100 | if (isUserType(next)) { |
| 94 | 101 | ++parser.idx; // skipping '(' |
| 95 | 102 | |
| @@ -121,6 +128,20 @@ | ||
| 121 | 128 | return className.startsWith(REVERSED_TYPE); |
| 122 | 129 | } |
| 123 | 130 | |
| 131 | + public static boolean isFrozen(String className) { | |
| 132 | + return className.startsWith(FROZEN_TYPE); | |
| 133 | + } | |
| 134 | + | |
| 135 | + private static String getNestedClassName(String className) { | |
| 136 | + Parser p = new Parser(className, 0); | |
| 137 | + p.parseNextName(); | |
| 138 | + List<String> l = p.getTypeParameters(); | |
| 139 | + if (l.size() != 1) | |
| 140 | + throw new IllegalStateException(); | |
| 141 | + className = l.get(0); | |
| 142 | + return className; | |
| 143 | + } | |
| 144 | + | |
| 124 | 145 | public static boolean isUserType(String className) { |
| 125 | 146 | return className.startsWith(UDT_TYPE); |
| 126 | 147 | } |
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +148 −32
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import com.google.common.base.Objects; |
| 25 | 25 | import com.google.common.collect.ImmutableList; |
| 26 | 26 | import com.google.common.collect.ImmutableSet; |
| 27 | +import com.google.common.reflect.TypeToken; | |
| 27 | 28 | import org.jboss.netty.buffer.ChannelBuffer; |
| 28 | 29 | |
| 29 | 30 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| @@ -165,26 +166,6 @@ | ||
| 165 | 166 | this.name = name; |
| 166 | 167 | } |
| 167 | 168 | |
| 168 | - | |
| 169 | - /** | |
| 170 | - * Returns whether this data type is frozen. | |
| 171 | - * <p> | |
| 172 | - * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in | |
| 173 | - * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields. | |
| 174 | - * | |
| 175 | - * @return whether this data type is frozen. | |
| 176 | - */ | |
| 177 | - public boolean isFrozen() { | |
| 178 | - // With Cassandra 2.1.0, this is straightforward; in future versions, "frozenness" will be stored in the database. | |
| 179 | - switch (name) { | |
| 180 | - case UDT: | |
| 181 | - case TUPLE: | |
| 182 | - return true; | |
| 183 | - default: | |
| 184 | - return false; | |
| 185 | - } | |
| 186 | - } | |
| 187 | - | |
| 188 | 169 | static DataType decode(ChannelBuffer buffer) { |
| 189 | 170 | Name name = Name.fromProtocolId(buffer.readUnsignedShort()); |
| 190 | 171 | switch (name) { |
| @@ -374,23 +355,70 @@ | ||
| 374 | 355 | * Returns the type of lists of {@code elementType} elements. |
| 375 | 356 | * |
| 376 | 357 | * @param elementType the type of the list elements. |
| 358 | + * @param frozen whether the list is frozen. | |
| 377 | 359 | * @return the type of lists of {@code elementType} elements. |
| 378 | 360 | */ |
| 361 | + public static DataType list(DataType elementType, boolean frozen) { | |
| 362 | + return new DataType.Collection(Name.LIST, ImmutableList.of(elementType), frozen); | |
| 363 | + } | |
| 364 | + | |
| 365 | + /** | |
| 366 | + * Returns the type of lists of "not frozen" {@code elementType} elements. | |
| 367 | + * <p> | |
| 368 | + * This is a shorthand for {@code list(elementType, false);}. | |
| 369 | + * | |
| 370 | + * @param elementType the type of the list elements. | |
| 371 | + * @return the type of lists of "not frozen" {@code elementType} elements. | |
| 372 | + */ | |
| 379 | 373 | public static DataType list(DataType elementType) { |
| 380 | - // TODO: for list, sets and maps, we could cache them (may or may not be worth it, but since we | |
| 381 | - // don't allow nesting of collections, even pregenerating all the lists/sets like we do for | |
| 382 | - // primitives wouldn't be very costly) | |
| 383 | - return new DataType.Collection(Name.LIST, ImmutableList.of(elementType)); | |
| 374 | + return list(elementType, false); | |
| 375 | + } | |
| 376 | + | |
| 377 | + /** | |
| 378 | + * Returns the type of lists of frozen {@code elementType} elements. | |
| 379 | + * <p> | |
| 380 | + * This is a shorthand for {@code list(elementType, true);}. | |
| 381 | + * | |
| 382 | + * @param elementType the type of the list elements. | |
| 383 | + * @return the type of lists of frozen {@code elementType} elements. | |
| 384 | + */ | |
| 385 | + public static DataType frozenList(DataType elementType) { | |
| 386 | + return list(elementType, true); | |
| 384 | 387 | } |
| 385 | 388 | |
| 386 | 389 | /** |
| 387 | 390 | * Returns the type of sets of {@code elementType} elements. |
| 388 | 391 | * |
| 389 | 392 | * @param elementType the type of the set elements. |
| 393 | + * @param frozen whether the set is frozen. | |
| 390 | 394 | * @return the type of sets of {@code elementType} elements. |
| 391 | 395 | */ |
| 396 | + public static DataType set(DataType elementType, boolean frozen) { | |
| 397 | + return new DataType.Collection(Name.SET, ImmutableList.of(elementType), frozen); | |
| 398 | + } | |
| 399 | + | |
| 400 | + /** | |
| 401 | + * Returns the type of "not frozen" sets of {@code elementType} elements. | |
| 402 | + * <p> | |
| 403 | + * This is a shorthand for {@code set(elementType, false);}. | |
| 404 | + * | |
| 405 | + * @param elementType the type of the set elements. | |
| 406 | + * @return the type of sets of "not frozen" {@code elementType} elements. | |
| 407 | + */ | |
| 392 | 408 | public static DataType set(DataType elementType) { |
| 393 | - return new DataType.Collection(Name.SET, ImmutableList.of(elementType)); | |
| 409 | + return set(elementType, false); | |
| 410 | + } | |
| 411 | + | |
| 412 | + /** | |
| 413 | + * Returns the type of frozen sets of {@code elementType} elements. | |
| 414 | + * <p> | |
| 415 | + * This is a shorthand for {@code set(elementType, true);}. | |
| 416 | + * | |
| 417 | + * @param elementType the type of the set elements. | |
| 418 | + * @return the type of frozen sets of {@code elementType} elements. | |
| 419 | + */ | |
| 420 | + public static DataType frozenSet(DataType elementType) { | |
| 421 | + return set(elementType, true); | |
| 394 | 422 | } |
| 395 | 423 | |
| 396 | 424 | /** |
| @@ -398,10 +426,37 @@ | ||
| 398 | 426 | * |
| 399 | 427 | * @param keyType the type of the map keys. |
| 400 | 428 | * @param valueType the type of the map values. |
| 401 | - * @return the type of map of {@code keyType} to {@code valueType} elements. | |
| 429 | + * @param frozen whether the map is frozen. | |
| 430 | + * @return the type of maps of {@code keyType} to {@code valueType} elements. | |
| 431 | + */ | |
| 432 | + public static DataType map(DataType keyType, DataType valueType, boolean frozen) { | |
| 433 | + return new DataType.Collection(Name.MAP, ImmutableList.of(keyType, valueType), frozen); | |
| 434 | + } | |
| 435 | + | |
| 436 | + /** | |
| 437 | + * Returns the type of "not frozen" maps of {@code keyType} to {@code valueType} elements. | |
| 438 | + * <p> | |
| 439 | + * This is a shorthand for {@code map(keyType, valueType, false);}. | |
| 440 | + * | |
| 441 | + * @param keyType the type of the map keys. | |
| 442 | + * @param valueType the type of the map values. | |
| 443 | + * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements. | |
| 402 | 444 | */ |
| 403 | 445 | public static DataType map(DataType keyType, DataType valueType) { |
| 404 | - return new DataType.Collection(Name.MAP, ImmutableList.of(keyType, valueType)); | |
| 446 | + return map(keyType, valueType, false); | |
| 447 | + } | |
| 448 | + | |
| 449 | + /** | |
| 450 | + * Returns the type of frozen maps of {@code keyType} to {@code valueType} elements. | |
| 451 | + * <p> | |
| 452 | + * This is a shorthand for {@code map(keyType, valueType, true);}. | |
| 453 | + * | |
| 454 | + * @param keyType the type of the map keys. | |
| 455 | + * @param valueType the type of the map values. | |
| 456 | + * @return the type of frozen maps of {@code keyType} to {@code valueType} elements. | |
| 457 | + */ | |
| 458 | + public static DataType frozenMap(DataType keyType, DataType valueType) { | |
| 459 | + return map(keyType, valueType, true); | |
| 405 | 460 | } |
| 406 | 461 | |
| 407 | 462 | /** |
| @@ -433,6 +488,16 @@ | ||
| 433 | 488 | return name; |
| 434 | 489 | } |
| 435 | 490 | |
| 491 | + /** | |
| 492 | + * Returns whether this data type is frozen. | |
| 493 | + * <p> | |
| 494 | + * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in | |
| 495 | + * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields. | |
| 496 | + * | |
| 497 | + * @return whether this data type is frozen. | |
| 498 | + */ | |
| 499 | + public abstract boolean isFrozen(); | |
| 500 | + | |
| 436 | 501 | /** |
| 437 | 502 | * Returns the type arguments of this type. |
| 438 | 503 | * <p> |
| @@ -454,6 +519,8 @@ | ||
| 454 | 519 | return Collections.<DataType>emptyList(); |
| 455 | 520 | } |
| 456 | 521 | |
| 522 | + abstract boolean canBeDeserializedAs(TypeToken typeToken); | |
| 523 | + | |
| 457 | 524 | /** |
| 458 | 525 | * Returns the server-side class name for a custom type. |
| 459 | 526 | * |
| @@ -693,6 +760,16 @@ | ||
| 693 | 760 | super(name); |
| 694 | 761 | } |
| 695 | 762 | |
| 763 | + @Override | |
| 764 | + public boolean isFrozen() { | |
| 765 | + return false; | |
| 766 | + } | |
| 767 | + | |
| 768 | + @Override | |
| 769 | + boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 770 | + return typeToken.isAssignableFrom(getName().javaType); | |
| 771 | + } | |
| 772 | + | |
| 696 | 773 | @Override |
| 697 | 774 | TypeCodec<Object> codec(ProtocolVersion protocolVersion) { |
| 698 | 775 | return TypeCodec.createFor(name); |
| @@ -725,10 +802,35 @@ | ||
| 725 | 802 | private static class Collection extends DataType { |
| 726 | 803 | |
| 727 | 804 | private final List<DataType> typeArguments; |
| 805 | + private boolean frozen; | |
| 728 | 806 | |
| 729 | - private Collection(DataType.Name name, List<DataType> typeArguments) { | |
| 807 | + private Collection(DataType.Name name, List<DataType> typeArguments, boolean frozen) { | |
| 730 | 808 | super(name); |
| 731 | 809 | this.typeArguments = typeArguments; |
| 810 | + this.frozen = frozen; | |
| 811 | + } | |
| 812 | + | |
| 813 | + @Override | |
| 814 | + public boolean isFrozen() { | |
| 815 | + return frozen; | |
| 816 | + } | |
| 817 | + | |
| 818 | + @Override | |
| 819 | + @SuppressWarnings("unchecked") | |
| 820 | + boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 821 | + switch (name) { | |
| 822 | + case LIST: | |
| 823 | + return typeToken.getRawType().isAssignableFrom(List.class) && | |
| 824 | + typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])); | |
| 825 | + case SET: | |
| 826 | + return typeToken.getRawType().isAssignableFrom(Set.class) && | |
| 827 | + typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])); | |
| 828 | + case MAP: | |
| 829 | + return typeToken.getRawType().isAssignableFrom(Map.class) && | |
| 830 | + typeArguments.get(0).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[0])) && | |
| 831 | + typeArguments.get(1).canBeDeserializedAs(typeToken.resolveType(typeToken.getRawType().getTypeParameters()[1])); | |
| 832 | + } | |
| 833 | + throw new AssertionError(); | |
| 732 | 834 | } |
| 733 | 835 | |
| 734 | 836 | @SuppressWarnings("unchecked") |
| @@ -764,10 +866,14 @@ | ||
| 764 | 866 | |
| 765 | 867 | @Override |
| 766 | 868 | public String toString() { |
| 767 | - if (name == Name.MAP) | |
| 768 | - return String.format("%s<%s, %s>", name, typeArguments.get(0), typeArguments.get(1)); | |
| 769 | - else | |
| 770 | - return String.format("%s<%s>", name, typeArguments.get(0)); | |
| 869 | + if (name == Name.MAP) { | |
| 870 | + String template = frozen ? "frozen<%s<%s, %s>>" : "%s<%s, %s>"; | |
| 871 | + return String.format(template, name, typeArguments.get(0), typeArguments.get(1)); | |
| 872 | + } | |
| 873 | + else { | |
| 874 | + String template = frozen ? "frozen<%s<%s>>" : "%s<%s>"; | |
| 875 | + return String.format(template, name, typeArguments.get(0)); | |
| 876 | + } | |
| 771 | 877 | } |
| 772 | 878 | } |
| 773 | 879 | |
| @@ -780,6 +886,16 @@ | ||
| 780 | 886 | this.customClassName = className; |
| 781 | 887 | } |
| 782 | 888 | |
| 889 | + @Override | |
| 890 | + public boolean isFrozen() { | |
| 891 | + return false; | |
| 892 | + } | |
| 893 | + | |
| 894 | + @Override | |
| 895 | + boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 896 | + return typeToken.getRawType().getName().equals(customClassName); | |
| 897 | + } | |
| 898 | + | |
| 783 | 899 | @SuppressWarnings("unchecked") |
| 784 | 900 | @Override |
| 785 | 901 | TypeCodec<Object> codec(ProtocolVersion protocolVersion) { |
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +82 −7
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -206,55 +208,128 @@ | ||
| 206 | 208 | |
| 207 | 209 | /** |
| 208 | 210 | * Returns the {@code i}th value as a list. |
| 211 | + * <p> | |
| 212 | + * If the type of the elements is generic, use {@link #getList(int, TypeToken)}. | |
| 209 | 213 | * |
| 210 | 214 | * @param i the index ({@code 0 <= i < size()}) to retrieve. |
| 211 | 215 | * @param elementsClass the class for the elements of the list to retrieve. |
| 212 | 216 | * @return the value of the {@code i}th element as a list of |
| 213 | - * {@code elementsClass} objects. If the value is NULL, an empty list is | |
| 217 | + * {@code T} objects. If the value is NULL, an empty list is | |
| 214 | 218 | * returned (note that Cassandra makes no difference between an empty list |
| 215 | 219 | * and column of type list that is not set). The returned list is immutable. |
| 216 | 220 | * |
| 217 | 221 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 218 | 222 | * @throws InvalidTypeException if value {@code i} is not a list or if its |
| 219 | - * elements are not of class {@code elementsClass}. | |
| 223 | + * elements are not of class {@code T}. | |
| 220 | 224 | */ |
| 221 | 225 | public <T> List<T> getList(int i, Class<T> elementsClass); |
| 222 | 226 | |
| 227 | + /** | |
| 228 | + * Returns the {@code i}th value as a list. | |
| 229 | + * <p> | |
| 230 | + * Use this variant with nested collections, which produce a generic element type: | |
| 231 | + * <pre> | |
| 232 | + * {@code List<List<String>> l = row.getList(1, new TypeToken<List<String>>() {});} | |
| 233 | + * </pre> | |
| 234 | + * | |
| 235 | + * @param i the index ({@code 0 <= i < size()}) to retrieve. | |
| 236 | + * @param elementsType the type of the elements of the list to retrieve. | |
| 237 | + * @return the value of the {@code i}th element as a list of | |
| 238 | + * {@code T} objects. If the value is NULL, an empty list is | |
| 239 | + * returned (note that Cassandra makes no difference between an empty list | |
| 240 | + * and column of type list that is not set). The returned list is immutable. | |
| 241 | + * | |
| 242 | + * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. | |
| 243 | + * @throws InvalidTypeException if value {@code i} is not a list or if its | |
| 244 | + * elements are not of class {@code T}. | |
| 245 | + */ | |
| 246 | + public <T> List<T> getList(int i, TypeToken<T> elementsType); | |
| 247 | + | |
| 223 | 248 | /** |
| 224 | 249 | * Returns the {@code i}th value as a set. |
| 250 | + * <p> | |
| 251 | + * If the type of the elements is generic, use {@link #getSet(int, TypeToken)}. | |
| 225 | 252 | * |
| 226 | 253 | * @param i the index ({@code 0 <= i < size()}) to retrieve. |
| 227 | 254 | * @param elementsClass the class for the elements of the set to retrieve. |
| 228 | 255 | * @return the value of the {@code i}th element as a set of |
| 229 | - * {@code elementsClass} objects. If the value is NULL, an empty set is | |
| 256 | + * {@code T} objects. If the value is NULL, an empty set is | |
| 230 | 257 | * returned (note that Cassandra makes no difference between an empty set |
| 231 | 258 | * and column of type set that is not set). The returned set is immutable. |
| 232 | 259 | * |
| 233 | 260 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 234 | 261 | * @throws InvalidTypeException if value {@code i} is not a set or if its |
| 235 | - * elements are not of class {@code elementsClass}. | |
| 262 | + * elements are not of class {@code T}. | |
| 236 | 263 | */ |
| 237 | 264 | public <T> Set<T> getSet(int i, Class<T> elementsClass); |
| 238 | 265 | |
| 266 | + /** | |
| 267 | + * Returns the {@code i}th value as a set. | |
| 268 | + * <p> | |
| 269 | + * Use this variant with nested collections, which produce a generic element type: | |
| 270 | + * <pre> | |
| 271 | + * {@code Set<List<String>> l = row.getSet(1, new TypeToken<List<String>>() {});} | |
| 272 | + * </pre> | |
| 273 | + * | |
| 274 | + * @param i the index ({@code 0 <= i < size()}) to retrieve. | |
| 275 | + * @param elementsType the type for the elements of the set to retrieve. | |
| 276 | + * @return the value of the {@code i}th element as a set of | |
| 277 | + * {@code T} objects. If the value is NULL, an empty set is | |
| 278 | + * returned (note that Cassandra makes no difference between an empty set | |
| 279 | + * and column of type set that is not set). The returned set is immutable. | |
| 280 | + * | |
| 281 | + * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. | |
| 282 | + * @throws InvalidTypeException if value {@code i} is not a set or if its | |
| 283 | + * elements are not of class {@code T}. | |
| 284 | + */ | |
| 285 | + public <T> Set<T> getSet(int i, TypeToken<T> elementsType); | |
| 286 | + | |
| 239 | 287 | /** |
| 240 | 288 | * Returns the {@code i}th value as a map. |
| 289 | + * <p> | |
| 290 | + * If the type of the keys and/or values is generic, use {@link #getMap(int, TypeToken, TypeToken)}. | |
| 241 | 291 | * |
| 242 | 292 | * @param i the index ({@code 0 <= i < size()}) to retrieve. |
| 243 | 293 | * @param keysClass the class for the keys of the map to retrieve. |
| 244 | 294 | * @param valuesClass the class for the values of the map to retrieve. |
| 245 | 295 | * @return the value of the {@code i}th element as a map of |
| 246 | - * {@code keysClass} to {@code valuesClass} objects. If the value is NULL, | |
| 296 | + * {@code K} to {@code V} objects. If the value is NULL, | |
| 247 | 297 | * an empty map is returned (note that Cassandra makes no difference |
| 248 | 298 | * between an empty map and column of type map that is not set). The |
| 249 | 299 | * returned map is immutable. |
| 250 | 300 | * |
| 251 | 301 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 252 | 302 | * @throws InvalidTypeException if value {@code i} is not a map, if its |
| 253 | - * keys are not of class {@code keysClass} or if its values are not of | |
| 254 | - * class {@code valuesClass}. | |
| 303 | + * keys are not of class {@code K} or if its values are not of | |
| 304 | + * class {@code V}. | |
| 255 | 305 | */ |
| 256 | 306 | public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass); |
| 257 | 307 | |
| 308 | + | |
| 309 | + /** | |
| 310 | + * Returns the {@code i}th value as a map. | |
| 311 | + * <p> | |
| 312 | + * Use this variant with nested collections, which produce a generic element type: | |
| 313 | + * <pre> | |
| 314 | + * {@code Map<Int, List<String>> l = row.getMap(1, TypeToken.of(Integer.class), new TypeToken<List<String>>() {});} | |
| 315 | + * </pre> | |
| 316 | + * | |
| 317 | + * @param i the index ({@code 0 <= i < size()}) to retrieve. | |
| 318 | + * @param keysType the type for the keys of the map to retrieve. | |
| 319 | + * @param valuesType the type for the values of the map to retrieve. | |
| 320 | + * @return the value of the {@code i}th element as a map of | |
| 321 | + * {@code K} to {@code V} objects. If the value is NULL, | |
| 322 | + * an empty map is returned (note that Cassandra makes no difference | |
| 323 | + * between an empty map and column of type map that is not set). The | |
| 324 | + * returned map is immutable. | |
| 325 | + * | |
| 326 | + * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. | |
| 327 | + * @throws InvalidTypeException if value {@code i} is not a map, if its | |
| 328 | + * keys are not of class {@code K} or if its values are not of | |
| 329 | + * class {@code V}. | |
| 330 | + */ | |
| 331 | + public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType); | |
| 332 | + | |
| 258 | 333 | /** |
| 259 | 334 | * Return the {@code i}th value as a UDT value. |
| 260 | 335 | * |
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +81 −7
| @@ -21,6 +21,8 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | + | |
| 24 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 27 | |
| 26 | 28 | /** |
| @@ -206,55 +208,127 @@ | ||
| 206 | 208 | |
| 207 | 209 | /** |
| 208 | 210 | * Returns the value for {@code name} as a list. |
| 211 | + * <p> | |
| 212 | + * If the type of the elements is generic, use {@link #getList(String, TypeToken)}. | |
| 209 | 213 | * |
| 210 | 214 | * @param name the name to retrieve. |
| 211 | 215 | * @param elementsClass the class for the elements of the list to retrieve. |
| 212 | 216 | * @return the value of the {@code i}th element as a list of |
| 213 | - * {@code elementsClass} objects. If the value is NULL, an empty list is | |
| 217 | + * {@code T} objects. If the value is NULL, an empty list is | |
| 214 | 218 | * returned (note that Cassandra makes no difference between an empty list |
| 215 | 219 | * and column of type list that is not set). The returned list is immutable. |
| 216 | 220 | * |
| 217 | 221 | * @throws IllegalArgumentException if {@code name} is not valid name for this object. |
| 218 | 222 | * @throws InvalidTypeException if value {@code name} is not a list or if its |
| 219 | - * elements are not of class {@code elementsClass}. | |
| 223 | + * elements are not of class {@code T}. | |
| 220 | 224 | */ |
| 221 | 225 | public <T> List<T> getList(String name, Class<T> elementsClass); |
| 222 | 226 | |
| 227 | + /** | |
| 228 | + * Returns the value for {@code name} as a list. | |
| 229 | + * <p> | |
| 230 | + * Use this variant with nested collections, which produce a generic element type: | |
| 231 | + * <pre> | |
| 232 | + * {@code List<List<String>> l = row.getList("theColumn", new TypeToken<List<String>>() {});} | |
| 233 | + * </pre> | |
| 234 | + * | |
| 235 | + * @param name the name to retrieve. | |
| 236 | + * @param elementsType the type for the elements of the list to retrieve. | |
| 237 | + * @return the value of the {@code i}th element as a list of | |
| 238 | + * {@code T} objects. If the value is NULL, an empty list is | |
| 239 | + * returned (note that Cassandra makes no difference between an empty list | |
| 240 | + * and column of type list that is not set). The returned list is immutable. | |
| 241 | + * | |
| 242 | + * @throws IllegalArgumentException if {@code name} is not valid name for this object. | |
| 243 | + * @throws InvalidTypeException if value {@code name} is not a list or if its | |
| 244 | + * elements are not of class {@code T}. | |
| 245 | + */ | |
| 246 | + public <T> List<T> getList(String name, TypeToken<T> elementsType); | |
| 247 | + | |
| 223 | 248 | /** |
| 224 | 249 | * Returns the value for {@code name} as a set. |
| 250 | + * <p> | |
| 251 | + * If the type of the elements is generic, use {@link #getSet(String, TypeToken)}. | |
| 225 | 252 | * |
| 226 | 253 | * @param name the name to retrieve. |
| 227 | 254 | * @param elementsClass the class for the elements of the set to retrieve. |
| 228 | 255 | * @return the value of the {@code i}th element as a set of |
| 229 | - * {@code elementsClass} objects. If the value is NULL, an empty set is | |
| 256 | + * {@code T} objects. If the value is NULL, an empty set is | |
| 230 | 257 | * returned (note that Cassandra makes no difference between an empty set |
| 231 | 258 | * and column of type set that is not set). The returned set is immutable. |
| 232 | 259 | * |
| 233 | 260 | * @throws IllegalArgumentException if {@code name} is not valid name for this object. |
| 234 | 261 | * @throws InvalidTypeException if value {@code name} is not a set or if its |
| 235 | - * elements are not of class {@code elementsClass}. | |
| 262 | + * elements are not of class {@code T}. | |
| 236 | 263 | */ |
| 237 | 264 | public <T> Set<T> getSet(String name, Class<T> elementsClass); |
| 238 | 265 | |
| 266 | + /** | |
| 267 | + * Returns the value for {@code name} as a set. | |
| 268 | + * <p> | |
| 269 | + * Use this variant with nested collections, which produce a generic element type: | |
| 270 | + * <pre> | |
| 271 | + * {@code Set<List<String>> l = row.getSet("theColumn", new TypeToken<List<String>>() {});} | |
| 272 | + * </pre> | |
| 273 | + * | |
| 274 | + * @param name the name to retrieve. | |
| 275 | + * @param elementsType the type for the elements of the set to retrieve. | |
| 276 | + * @return the value of the {@code i}th element as a set of | |
| 277 | + * {@code T} objects. If the value is NULL, an empty set is | |
| 278 | + * returned (note that Cassandra makes no difference between an empty set | |
| 279 | + * and column of type set that is not set). The returned set is immutable. | |
| 280 | + * | |
| 281 | + * @throws IllegalArgumentException if {@code name} is not valid name for this object. | |
| 282 | + * @throws InvalidTypeException if value {@code name} is not a set or if its | |
| 283 | + * elements are not of class {@code T}. | |
| 284 | + */ | |
| 285 | + public <T> Set<T> getSet(String name, TypeToken<T> elementsType); | |
| 286 | + | |
| 239 | 287 | /** |
| 240 | 288 | * Returns the value for {@code name} as a map. |
| 289 | + * <p> | |
| 290 | + * If the type of the keys and/or values is generic, use {@link #getMap(String, TypeToken, TypeToken)}. | |
| 241 | 291 | * |
| 242 | 292 | * @param name the name to retrieve. |
| 243 | 293 | * @param keysClass the class for the keys of the map to retrieve. |
| 244 | 294 | * @param valuesClass the class for the values of the map to retrieve. |
| 245 | 295 | * @return the value of {@code name} as a map of |
| 246 | - * {@code keysClass} to {@code valuesClass} objects. If the value is NULL, | |
| 296 | + * {@code K} to {@code V} objects. If the value is NULL, | |
| 247 | 297 | * an empty map is returned (note that Cassandra makes no difference |
| 248 | 298 | * between an empty map and column of type map that is not set). The |
| 249 | 299 | * returned map is immutable. |
| 250 | 300 | * |
| 251 | 301 | * @throws IllegalArgumentException if {@code name} is not valid name for this object. |
| 252 | 302 | * @throws InvalidTypeException if value {@code name} is not a map, if its |
| 253 | - * keys are not of class {@code keysClass} or if its values are not of | |
| 254 | - * class {@code valuesClass}. | |
| 303 | + * keys are not of class {@code K} or if its values are not of | |
| 304 | + * class {@code V}. | |
| 255 | 305 | */ |
| 256 | 306 | public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass); |
| 257 | 307 | |
| 308 | + /** | |
| 309 | + * Returns the value for {@code name} as a map. | |
| 310 | + * <p> | |
| 311 | + * Use this variant with nested collections, which produce a generic element type: | |
| 312 | + * <pre> | |
| 313 | + * {@code Map<Int, List<String>> l = row.getMap("theColumn", TypeToken.of(Integer.class), new TypeToken<List<String>>() {});} | |
| 314 | + * </pre> | |
| 315 | + * | |
| 316 | + * @param name the name to retrieve. | |
| 317 | + * @param keysType the class for the keys of the map to retrieve. | |
| 318 | + * @param valuesType the class for the values of the map to retrieve. | |
| 319 | + * @return the value of {@code name} as a map of | |
| 320 | + * {@code K} to {@code V} objects. If the value is NULL, | |
| 321 | + * an empty map is returned (note that Cassandra makes no difference | |
| 322 | + * between an empty map and column of type map that is not set). The | |
| 323 | + * returned map is immutable. | |
| 324 | + * | |
| 325 | + * @throws IllegalArgumentException if {@code name} is not valid name for this object. | |
| 326 | + * @throws InvalidTypeException if value {@code name} is not a map, if its | |
| 327 | + * keys are not of class {@code K} or if its values are not of | |
| 328 | + * class {@code V}. | |
| 329 | + */ | |
| 330 | + public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType); | |
| 331 | + | |
| 258 | 332 | /** |
| 259 | 333 | * Return the value for {@code name} as a UDT value. |
| 260 | 334 | * |
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +13 −2
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | 20 | import com.google.common.collect.ImmutableList; |
| 21 | +import com.google.common.reflect.TypeToken; | |
| 21 | 22 | |
| 22 | 23 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 23 | 24 | |
| @@ -99,6 +100,16 @@ | ||
| 99 | 100 | return t; |
| 100 | 101 | } |
| 101 | 102 | |
| 103 | + @Override | |
| 104 | + public boolean isFrozen() { | |
| 105 | + return true; | |
| 106 | + } | |
| 107 | + | |
| 108 | + @Override | |
| 109 | + boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 110 | + return typeToken.isAssignableFrom(getName().javaType); | |
| 111 | + } | |
| 112 | + | |
| 102 | 113 | @Override |
| 103 | 114 | public int hashCode() { |
| 104 | 115 | return Arrays.hashCode(new Object[]{ name, types }); |
| @@ -117,9 +128,9 @@ | ||
| 117 | 128 | public String toString() { |
| 118 | 129 | StringBuilder sb = new StringBuilder(); |
| 119 | 130 | for (DataType type : types) { |
| 120 | - sb.append(sb.length() == 0 ? "tuple<" : ", "); | |
| 131 | + sb.append(sb.length() == 0 ? "frozen<tuple<" : ", "); | |
| 121 | 132 | sb.append(type); |
| 122 | 133 | } |
| 123 | - return sb.append(">").toString(); | |
| 134 | + return sb.append(">>").toString(); | |
| 124 | 135 | } |
| 125 | 136 | } |
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +13 −2
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | |
| 20 | 20 | import com.google.common.collect.ImmutableMap; |
| 21 | 21 | import com.google.common.collect.Iterators; |
| 22 | +import com.google.common.reflect.TypeToken; | |
| 22 | 23 | |
| 23 | 24 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 24 | 25 | |
| @@ -166,6 +167,16 @@ | ||
| 166 | 167 | return byIdx[idx[0]].getType(); |
| 167 | 168 | } |
| 168 | 169 | |
| 170 | + @Override | |
| 171 | + public boolean isFrozen() { | |
| 172 | + return true; | |
| 173 | + } | |
| 174 | + | |
| 175 | + @Override | |
| 176 | + boolean canBeDeserializedAs(TypeToken typeToken) { | |
| 177 | + return typeToken.isAssignableFrom(getName().javaType); | |
| 178 | + } | |
| 179 | + | |
| 169 | 180 | @Override |
| 170 | 181 | public final int hashCode() { |
| 171 | 182 | return Arrays.hashCode(new Object[]{ name, keyspace, typeName, byIdx }); |
| @@ -225,12 +236,12 @@ | ||
| 225 | 236 | TableMetadata.newLine(sb, formatted); |
| 226 | 237 | } |
| 227 | 238 | |
| 228 | - return sb.append(')').toString(); | |
| 239 | + return sb.append(");").toString(); | |
| 229 | 240 | } |
| 230 | 241 | |
| 231 | 242 | @Override |
| 232 | 243 | public String toString() { |
| 233 | - return Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName()); | |
| 244 | + return "frozen<" + Metadata.escapeId(getKeyspace()) + '.' + Metadata.escapeId(getTypeName()) + ">"; | |
| 234 | 245 | } |
| 235 | 246 | |
| 236 | 247 | // We don't want to expose that, it's already exposed through DataType.parse |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +1 −2
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.List; |
| 21 | 20 | |
| @@ -361,7 +360,7 @@ | ||
| 361 | 360 | StringBuilder sb = new StringBuilder(); |
| 362 | 361 | Utils.appendName(columnName, sb); |
| 363 | 362 | sb.append('['); |
| 364 | - Utils.appendFlatValue(key, sb); | |
| 363 | + Utils.appendValue(key, sb); | |
| 365 | 364 | return column(sb.append(']').toString()); |
| 366 | 365 | } |
| 367 | 366 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +5 −14
| @@ -26,7 +26,6 @@ | ||
| 26 | 26 | import com.datastax.driver.core.ProtocolVersion; |
| 27 | 27 | import com.datastax.driver.core.TupleValue; |
| 28 | 28 | import com.datastax.driver.core.UDTValue; |
| 29 | -import com.datastax.driver.core.utils.Bytes; | |
| 30 | 29 | |
| 31 | 30 | // Static utilities private to the query builder |
| 32 | 31 | abstract class Utils { |
| @@ -96,7 +95,7 @@ | ||
| 96 | 95 | return sb; |
| 97 | 96 | } |
| 98 | 97 | |
| 99 | - private static StringBuilder appendValue(Object value, StringBuilder sb) { | |
| 98 | + static StringBuilder appendValue(Object value, StringBuilder sb) { | |
| 100 | 99 | // That is kind of lame but lacking a better solution |
| 101 | 100 | if (appendValueIfLiteral(value, sb)) |
| 102 | 101 | return sb; |
| @@ -114,14 +113,6 @@ | ||
| 114 | 113 | return sb; |
| 115 | 114 | } |
| 116 | 115 | |
| 117 | - static StringBuilder appendFlatValue(Object value, StringBuilder sb) { | |
| 118 | - if (appendValueIfLiteral(value, sb)) | |
| 119 | - return sb; | |
| 120 | - | |
| 121 | - appendStringIfValid(value, sb); | |
| 122 | - return sb; | |
| 123 | - } | |
| 124 | - | |
| 125 | 116 | private static void appendStringIfValid(Object value, StringBuilder sb) { |
| 126 | 117 | if (value instanceof RawString) { |
| 127 | 118 | sb.append(value.toString()); |
| @@ -205,7 +196,7 @@ | ||
| 205 | 196 | for (int i = 0; i < l.size(); i++) { |
| 206 | 197 | if (i > 0) |
| 207 | 198 | sb.append(','); |
| 208 | - appendFlatValue(l.get(i), sb); | |
| 199 | + appendValue(l.get(i), sb); | |
| 209 | 200 | } |
| 210 | 201 | sb.append(']'); |
| 211 | 202 | return sb; |
| @@ -216,7 +207,7 @@ | ||
| 216 | 207 | boolean first = true; |
| 217 | 208 | for (Object elt : s) { |
| 218 | 209 | if (first) first = false; else sb.append(','); |
| 219 | - appendFlatValue(elt, sb); | |
| 210 | + appendValue(elt, sb); | |
| 220 | 211 | } |
| 221 | 212 | sb.append('}'); |
| 222 | 213 | return sb; |
| @@ -230,9 +221,9 @@ | ||
| 230 | 221 | first = false; |
| 231 | 222 | else |
| 232 | 223 | sb.append(','); |
| 233 | - appendFlatValue(entry.getKey(), sb); | |
| 224 | + appendValue(entry.getKey(), sb); | |
| 234 | 225 | sb.append(':'); |
| 235 | - appendFlatValue(entry.getValue(), sb); | |
| 226 | + appendValue(entry.getValue(), sb); | |
| 236 | 227 | } |
| 237 | 228 | sb.append('}'); |
| 238 | 229 | return sb; |
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
| @@ -15,4 +15,8 @@ | ||
| 15 | 15 | public static TokenRangeAssert assertThat(TokenRange range) { |
| 16 | 16 | return new TokenRangeAssert(range); |
| 17 | 17 | } |
| 18 | + | |
| 19 | + public static DataTypeAssert assertThat(DataType type) { | |
| 20 | + return new DataTypeAssert(type); | |
| 21 | + } | |
| 18 | 22 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CassandraTypeParserTest.java +26 −3
| @@ -17,10 +17,15 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.Arrays; |
| 19 | 19 | import java.util.Iterator; |
| 20 | -import java.util.List; | |
| 21 | 20 | |
| 22 | 21 | import org.testng.annotations.Test; |
| 23 | -import static org.testng.Assert.*; | |
| 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; | |
| 24 | 29 | |
| 25 | 30 | public class CassandraTypeParserTest { |
| 26 | 31 | |
| @@ -44,7 +49,7 @@ | ||
| 44 | 49 | public void parseWithCompositeTest() { |
| 45 | 50 | |
| 46 | 51 | String s = "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type, org.apache.cassandra.db.marshal.UTF8Type,"; |
| 47 | - s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))"; | |
| 52 | + s += "org.apache.cassandra.db.marshal.ColumnToCollectionType(6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))"; | |
| 48 | 53 | CassandraTypeParser.ParseResult r1 = CassandraTypeParser.parseWithComposite(s); |
| 49 | 54 | assertTrue(r1.isComposite); |
| 50 | 55 | assertEquals(r1.types, Arrays.asList(DataType.cint(), DataType.text())); |
| @@ -106,4 +111,22 @@ | ||
| 106 | 111 | assertEquals(type.getComponentTypes().get(1), DataType.text()); |
| 107 | 112 | assertEquals(type.getComponentTypes().get(2), DataType.cfloat()); |
| 108 | 113 | } |
| 114 | + | |
| 115 | + @Test(groups = "unit") | |
| 116 | + public void parseNestedCollectionTest() { | |
| 117 | + // map<text, frozen<map<int,int>>> | |
| 118 | + 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)))"; | |
| 119 | + | |
| 120 | + DataType parentMap = CassandraTypeParser.parseOne(s); | |
| 121 | + assertThat(parentMap) | |
| 122 | + .hasName(DataType.Name.MAP) | |
| 123 | + .isNotFrozen() | |
| 124 | + .hasTypeArgument(0, DataType.text()); | |
| 125 | + | |
| 126 | + DataType childMap = parentMap.getTypeArguments().get(1); | |
| 127 | + assertThat(childMap) | |
| 128 | + .hasName(DataType.Name.MAP) | |
| 129 | + .isFrozen() | |
| 130 | + .hasTypeArguments(DataType.cint(), DataType.cint()); | |
| 131 | + } | |
| 109 | 132 | } |
added driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +47 −0
| @@ -0,0 +1,47 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import com.google.common.reflect.TypeToken; | |
| 4 | +import org.assertj.core.api.AbstractAssert; | |
| 5 | + | |
| 6 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 7 | + | |
| 8 | +public class DataTypeAssert extends AbstractAssert<DataTypeAssert, DataType> { | |
| 9 | + public DataTypeAssert(DataType actual) { | |
| 10 | + super(actual, DataTypeAssert.class); | |
| 11 | + } | |
| 12 | + | |
| 13 | + public DataTypeAssert hasName(DataType.Name name) { | |
| 14 | + assertThat(actual.name).isEqualTo(name); | |
| 15 | + return this; | |
| 16 | + } | |
| 17 | + | |
| 18 | + public DataTypeAssert isFrozen() { | |
| 19 | + assertThat(actual.isFrozen()).isTrue(); | |
| 20 | + return this; | |
| 21 | + } | |
| 22 | + | |
| 23 | + public DataTypeAssert isNotFrozen() { | |
| 24 | + assertThat(actual.isFrozen()).isFalse(); | |
| 25 | + return this; | |
| 26 | + } | |
| 27 | + | |
| 28 | + public DataTypeAssert canBeDeserializedAs(TypeToken typeToken) { | |
| 29 | + assertThat(actual.canBeDeserializedAs(typeToken)).isTrue(); | |
| 30 | + return this; | |
| 31 | + } | |
| 32 | + | |
| 33 | + public DataTypeAssert cannotBeDeserializedAs(TypeToken typeToken) { | |
| 34 | + assertThat(actual.canBeDeserializedAs(typeToken)).isFalse(); | |
| 35 | + return this; | |
| 36 | + } | |
| 37 | + | |
| 38 | + public DataTypeAssert hasTypeArgument(int position, DataType expected) { | |
| 39 | + assertThat(actual.getTypeArguments().get(position)).isEqualTo(expected); | |
| 40 | + return this; | |
| 41 | + } | |
| 42 | + | |
| 43 | + public DataTypeAssert hasTypeArguments(DataType... expected) { | |
| 44 | + assertThat(actual.getTypeArguments()).containsExactly(expected); | |
| 45 | + return this; | |
| 46 | + } | |
| 47 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +138 −556
| @@ -15,627 +15,209 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.math.BigDecimal; | |
| 19 | -import java.math.BigInteger; | |
| 20 | -import java.net.InetAddress; | |
| 21 | -import java.nio.ByteBuffer; | |
| 22 | -import java.text.SimpleDateFormat; | |
| 23 | -import java.util.*; | |
| 24 | - | |
| 25 | -import com.google.common.collect.ImmutableSet; | |
| 26 | - | |
| 18 | +import java.util.Collection; | |
| 19 | +import java.util.List; | |
| 20 | +import java.util.Map; | |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 22 | + | |
| 23 | +import com.google.common.collect.ImmutableList; | |
| 24 | +import com.google.common.collect.ImmutableMap; | |
| 25 | +import com.google.common.collect.Lists; | |
| 26 | +import com.google.common.collect.Sets; | |
| 27 | +import org.slf4j.Logger; | |
| 28 | +import org.slf4j.LoggerFactory; | |
| 27 | 29 | import org.testng.annotations.Test; |
| 28 | 30 | |
| 29 | -import static com.datastax.driver.core.DataTypeTest.exclude; | |
| 30 | -import static org.testng.Assert.assertEquals; | |
| 31 | -import static org.testng.Assert.assertTrue; | |
| 31 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 32 | 32 | |
| 33 | 33 | import com.datastax.driver.core.utils.CassandraVersion; |
| 34 | 34 | |
| 35 | 35 | /** |
| 36 | - * Tests DataType class to ensure data sent in is the same as data received | |
| 37 | - * All tests are executed via a Simple Statements | |
| 38 | - * Counters are the only datatype not tested within the entirety of the suite. | |
| 39 | - * There is, however, an isolated test case that needs to be implemented. | |
| 40 | - * All statements and sample data is easily exportable via the print_*() methods. | |
| 36 | + * The goal of this test is to cover the serialization and deserialization of datatypes. | |
| 37 | + * | |
| 38 | + * It creates a table with a column of a given type, inserts a value and then tries to retrieve it. | |
| 39 | + * There are 3 variants for the insert query: a raw string, a simple statement with a parameter | |
| 40 | + * (protocol > v2 only) and a prepared statement. | |
| 41 | + * This is repeated with a large number of datatypes. | |
| 41 | 42 | */ |
| 42 | 43 | public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster { |
| 44 | + private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class); | |
| 43 | 45 | |
| 44 | - private final static Set<DataType> DATA_TYPE_PRIMITIVES = DataType.allPrimitiveTypes(); | |
| 45 | - private final static Set<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = EnumSet.of(DataType.Name.MAP, DataType.Name.SET, DataType.Name.LIST); | |
| 46 | - | |
| 47 | - private final static String PRIMITIVE_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %2$s);"; | |
| 48 | - private final static String BASIC_SELECT_FORMAT = "SELECT k, v FROM %1$s;"; | |
| 49 | - | |
| 50 | - private final static String COLLECTION_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%2$s, %3$s);"; | |
| 51 | - private final static String MAP_INSERT_FORMAT = "INSERT INTO %1$s (k, v) VALUES (%3$s, {%2$s: %3$s});"; | |
| 46 | + List<TestTable> tables = allTables(); | |
| 47 | + VersionNumber cassandraVersion; | |
| 52 | 48 | |
| 53 | - private final static HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); | |
| 54 | - private final static HashMap<DataType, Object> SAMPLE_COLLECTIONS = getSampleCollections(); | |
| 49 | + enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED} | |
| 55 | 50 | |
| 56 | - private final static Collection<String> PRIMITIVE_INSERT_STATEMENTS = getPrimitiveInsertStatements(); | |
| 57 | - private final static HashMap<DataType, String> PRIMITIVE_SELECT_STATEMENTS = getPrimitiveSelectStatements(); | |
| 58 | - | |
| 59 | - private final static Collection<String> COLLECTION_INSERT_STATEMENTS = getCollectionInsertStatements(); | |
| 60 | - private final static HashMap<DataType, String> COLLECTION_SELECT_STATEMENTS = getCollectionSelectStatements(); | |
| 61 | - | |
| 62 | - /** | |
| 63 | - * Generates the table definitions that will be used in testing | |
| 64 | - */ | |
| 65 | 51 | @Override |
| 66 | 52 | protected Collection<String> getTableDefinitions() { |
| 67 | - ArrayList<String> tableDefinitions = new ArrayList<String>(); | |
| 68 | - | |
| 69 | - // Create primitive data type definitions | |
| 70 | - for (DataType dataType : DATA_TYPE_PRIMITIVES) { | |
| 71 | - if (exclude(dataType)) | |
| 72 | - continue; | |
| 73 | - | |
| 74 | - tableDefinitions.add(String.format("CREATE TABLE %1$s (k %2$s PRIMARY KEY, v %1$s)", dataType, dataType)); | |
| 75 | - } | |
| 53 | + Host host = cluster.getMetadata().getAllHosts().iterator().next(); | |
| 54 | + cassandraVersion = host.getCassandraVersion().nextStable(); | |
| 76 | 55 | |
| 77 | - // Create collection data type definitions | |
| 78 | - for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) { | |
| 79 | - // Create MAP data type definitions | |
| 80 | - if (dataTypeName == DataType.Name.MAP) { | |
| 81 | - for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) { | |
| 82 | - if (exclude(typeArgument1)) | |
| 83 | - continue; | |
| 84 | - | |
| 85 | - for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) { | |
| 86 | - if (exclude(typeArgument2)) | |
| 87 | - continue; | |
| 88 | - | |
| 89 | - tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s_%3$s (k %3$s PRIMARY KEY, v %1$s<%2$s, %3$s>)", dataTypeName, typeArgument1, typeArgument2)); | |
| 90 | - } | |
| 91 | - } | |
| 92 | - // Create SET and LIST data type definitions | |
| 93 | - } else { | |
| 94 | - for (DataType typeArgument : DATA_TYPE_PRIMITIVES) { | |
| 95 | - if (exclude(typeArgument)) | |
| 96 | - continue; | |
| 97 | - | |
| 98 | - tableDefinitions.add(String.format("CREATE TABLE %1$s_%2$s (k %2$s PRIMARY KEY, v %1$s<%2$s>)", dataTypeName, typeArgument)); | |
| 99 | - } | |
| 100 | - } | |
| 56 | + List<String> statements = Lists.newArrayList(); | |
| 57 | + for (TestTable table : tables) { | |
| 58 | + if (cassandraVersion.compareTo(table.minCassandraVersion) < 0) | |
| 59 | + logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}", | |
| 60 | + cassandraVersion, table.createStatement); | |
| 61 | + else | |
| 62 | + statements.add(table.createStatement); | |
| 101 | 63 | } |
| 102 | 64 | |
| 103 | - return tableDefinitions; | |
| 65 | + return statements; | |
| 104 | 66 | } |
| 105 | 67 | |
| 106 | - /** | |
| 107 | - * Generates the sample data that will be used in testing | |
| 108 | - */ | |
| 109 | - protected static HashMap<DataType, Object> getSampleData() { | |
| 110 | - HashMap<DataType, Object> sampleData = new HashMap<DataType, Object>(); | |
| 111 | - | |
| 112 | - for (DataType dataType : DATA_TYPE_PRIMITIVES) { | |
| 113 | - switch (dataType.getName()) { | |
| 114 | - case ASCII: | |
| 115 | - sampleData.put(dataType, new String("ascii")); | |
| 116 | - break; | |
| 117 | - case BIGINT: | |
| 118 | - sampleData.put(dataType, Long.MAX_VALUE); | |
| 119 | - break; | |
| 120 | - case BLOB: | |
| 121 | - ByteBuffer bb = ByteBuffer.allocate(58); | |
| 122 | - bb.putShort((short) 0xCAFE); | |
| 123 | - bb.flip(); | |
| 124 | - sampleData.put(dataType, bb); | |
| 125 | - break; | |
| 126 | - case BOOLEAN: | |
| 127 | - sampleData.put(dataType, Boolean.TRUE); | |
| 128 | - break; | |
| 129 | - case COUNTER: | |
| 130 | - // Not supported in an insert statement | |
| 131 | - break; | |
| 132 | - case DECIMAL: | |
| 133 | - sampleData.put(dataType, new BigDecimal("12.3E+7")); | |
| 134 | - break; | |
| 135 | - case DOUBLE: | |
| 136 | - sampleData.put(dataType, Double.MAX_VALUE); | |
| 137 | - break; | |
| 138 | - case FLOAT: | |
| 139 | - sampleData.put(dataType, Float.MAX_VALUE); | |
| 140 | - break; | |
| 141 | - case INET: | |
| 142 | - try { | |
| 143 | - sampleData.put(dataType, InetAddress.getByName("123.123.123.123")); | |
| 144 | - } catch (java.net.UnknownHostException e) {} | |
| 145 | - break; | |
| 146 | - case INT: | |
| 147 | - sampleData.put(dataType, Integer.MAX_VALUE); | |
| 148 | - break; | |
| 149 | - case TEXT: | |
| 150 | - sampleData.put(dataType, new String("text")); | |
| 151 | - break; | |
| 152 | - case TIMESTAMP: | |
| 153 | - sampleData.put(dataType, new Date(872835240000L)); | |
| 154 | - break; | |
| 155 | - case TIMEUUID: | |
| 156 | - sampleData.put(dataType, UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66")); | |
| 157 | - break; | |
| 158 | - case UUID: | |
| 159 | - sampleData.put(dataType, UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00")); | |
| 160 | - break; | |
| 161 | - case VARCHAR: | |
| 162 | - sampleData.put(dataType, new String("varchar")); | |
| 163 | - break; | |
| 164 | - case VARINT: | |
| 165 | - sampleData.put(dataType, new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000")); | |
| 166 | - break; | |
| 167 | - default: | |
| 168 | - throw new RuntimeException("Missing handling of " + dataType); | |
| 169 | - } | |
| 170 | - } | |
| 68 | + @Test(groups = "long") | |
| 69 | + public void should_insert_and_retrieve_data_with_legacy_statements() { | |
| 70 | + should_insert_and_retrieve_data(StatementType.RAW_STRING); | |
| 71 | + } | |
| 171 | 72 | |
| 172 | - return sampleData; | |
| 73 | + @Test(groups = "long") | |
| 74 | + public void should_insert_and_retrieve_data_with_prepared_statements() { | |
| 75 | + should_insert_and_retrieve_data(StatementType.PREPARED); | |
| 173 | 76 | } |
| 174 | 77 | |
| 175 | - protected static Object getCollectionSample(DataType.Name collectionType, DataType dataType) { | |
| 176 | - if(collectionType == DataType.Name.LIST) { | |
| 177 | - List<Object> theList = new ArrayList<Object>(); | |
| 178 | - theList.add(SAMPLE_DATA.get(dataType)); | |
| 179 | - theList.add(SAMPLE_DATA.get(dataType)); | |
| 180 | - return theList; | |
| 181 | - } | |
| 182 | - else if(collectionType == DataType.Name.SET) | |
| 183 | - return ImmutableSet.of(SAMPLE_DATA.get(dataType)); | |
| 184 | - else if(collectionType == DataType.Name.MAP) | |
| 185 | - return new HashMap<Object, Object>().put(SAMPLE_DATA.get(dataType), SAMPLE_DATA.get(dataType)); | |
| 186 | - else if(collectionType == DataType.Name.TUPLE) { | |
| 187 | - TupleType t = TupleType.of(dataType); | |
| 188 | - return t.newValue(SAMPLE_DATA.get(dataType)); | |
| 189 | - } | |
| 190 | - else | |
| 191 | - throw new IllegalArgumentException("Missing handling of non-primitive type" + collectionType); | |
| 78 | + @Test(groups = "long") | |
| 79 | + @CassandraVersion(major = 2.0, description = "Uses parameterized simple statements, which are only available with protocol v2") | |
| 80 | + public void should_insert_and_retrieve_data_with_parameterized_simple_statements() { | |
| 81 | + should_insert_and_retrieve_data(StatementType.SIMPLE_WITH_PARAM); | |
| 192 | 82 | } |
| 193 | 83 | |
| 194 | - /** | |
| 195 | - * Generates the sample collections that will be used in testing | |
| 196 | - */ | |
| 197 | - protected static HashMap<DataType, Object> getSampleCollections() { | |
| 198 | - HashMap<DataType, Object> sampleCollections = new HashMap<DataType, Object>(); | |
| 199 | - HashMap<DataType, Object> setAndListCollection; | |
| 200 | - HashMap<DataType, HashMap<DataType, Object>> mapCollection; | |
| 201 | - | |
| 202 | - for (DataType.Name dataTypeName : DATA_TYPE_NON_PRIMITIVE_NAMES) { | |
| 203 | - switch (dataTypeName) { | |
| 204 | - case LIST: | |
| 205 | - for (DataType typeArgument : DATA_TYPE_PRIMITIVES) { | |
| 206 | - if (exclude(typeArgument)) | |
| 207 | - continue; | |
| 208 | - | |
| 209 | - List<Object> list = new ArrayList<Object>(); | |
| 210 | - for (int i = 0; i < 5; i++) { | |
| 211 | - list.add(SAMPLE_DATA.get(typeArgument)); | |
| 212 | - } | |
| 213 | - | |
| 214 | - setAndListCollection = new HashMap<DataType, Object>(); | |
| 215 | - setAndListCollection.put(typeArgument, list); | |
| 216 | - sampleCollections.put(DataType.list(typeArgument), setAndListCollection); | |
| 217 | - } | |
| 84 | + protected void should_insert_and_retrieve_data(StatementType statementType) { | |
| 85 | + ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(); | |
| 86 | + | |
| 87 | + for (TestTable table : tables) { | |
| 88 | + if (cassandraVersion.compareTo(table.minCassandraVersion) < 0) | |
| 89 | + continue; | |
| 90 | + | |
| 91 | + switch (statementType) { | |
| 92 | + case RAW_STRING: | |
| 93 | + session.execute(table.insertStatement.replace("?", table.testColumnType.format(table.sampleValue))); | |
| 218 | 94 | break; |
| 219 | - case SET: | |
| 220 | - for (DataType typeArgument : DATA_TYPE_PRIMITIVES) { | |
| 221 | - if (exclude(typeArgument)) | |
| 222 | - continue; | |
| 223 | - | |
| 224 | - Set<Object> set = new HashSet<Object>(); | |
| 225 | - for (int i = 0; i < 5; i++) { | |
| 226 | - set.add(SAMPLE_DATA.get(typeArgument)); | |
| 227 | - } | |
| 228 | - | |
| 229 | - setAndListCollection = new HashMap<DataType, Object>(); | |
| 230 | - setAndListCollection.put(typeArgument, set); | |
| 231 | - sampleCollections.put(DataType.set(typeArgument), setAndListCollection); | |
| 232 | - } | |
| 95 | + case SIMPLE_WITH_PARAM: | |
| 96 | + session.execute(table.insertStatement, table.sampleValue); | |
| 233 | 97 | break; |
| 234 | - case MAP: | |
| 235 | - for (DataType typeArgument1 : DATA_TYPE_PRIMITIVES) { | |
| 236 | - if (exclude(typeArgument1)) | |
| 237 | - continue; | |
| 238 | - | |
| 239 | - for (DataType typeArgument2 : DATA_TYPE_PRIMITIVES) { | |
| 240 | - if (exclude(typeArgument2)) | |
| 241 | - continue; | |
| 242 | - | |
| 243 | - HashMap<DataType, Object> map = new HashMap<DataType, Object>(); | |
| 244 | - map.put(typeArgument1, SAMPLE_DATA.get(typeArgument2)); | |
| 245 | - | |
| 246 | - mapCollection = new HashMap<DataType, HashMap<DataType, Object>>(); | |
| 247 | - mapCollection.put(typeArgument1, map); | |
| 248 | - sampleCollections.put(DataType.map(typeArgument1, typeArgument2), mapCollection); | |
| 249 | - } | |
| 250 | - } | |
| 98 | + case PREPARED: | |
| 99 | + PreparedStatement ps = session.prepare(table.insertStatement); | |
| 100 | + session.execute(ps.bind(table.sampleValue)); | |
| 251 | 101 | break; |
| 252 | - default: | |
| 253 | - throw new RuntimeException("Missing handling of " + dataTypeName); | |
| 254 | 102 | } |
| 255 | - } | |
| 256 | - | |
| 257 | - return sampleCollections; | |
| 258 | - } | |
| 259 | 103 | |
| 260 | - /** | |
| 261 | - * Helper method to stringify SAMPLE_DATA for simple insert statements | |
| 262 | - */ | |
| 263 | - @SuppressWarnings("fallthrough") | |
| 264 | - private static String helperStringifiedData(DataType dataType) { | |
| 265 | - String value = SAMPLE_DATA.get(dataType).toString(); | |
| 266 | - | |
| 267 | - switch (dataType.getName()) { | |
| 268 | - case BLOB: | |
| 269 | - value = "0xCAFE"; | |
| 270 | - break; | |
| 271 | - | |
| 272 | - case INET: | |
| 273 | - InetAddress v1 = (InetAddress) SAMPLE_DATA.get(dataType); | |
| 274 | - value = String.format("'%s'", v1.getHostAddress()); | |
| 275 | - break; | |
| 276 | - | |
| 277 | - case TIMESTAMP: | |
| 278 | - Date v2 = (Date) SAMPLE_DATA.get(dataType); | |
| 279 | - value = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(v2); | |
| 280 | - case ASCII: | |
| 281 | - case TEXT: | |
| 282 | - case VARCHAR: | |
| 283 | - value = String.format("'%s'", value); | |
| 284 | - break; | |
| 285 | - | |
| 286 | - default: | |
| 287 | - break; | |
| 288 | - } | |
| 289 | - | |
| 290 | - return value; | |
| 291 | - } | |
| 292 | - | |
| 293 | - /** | |
| 294 | - * Generates the insert statements that will be used in testing | |
| 295 | - */ | |
| 296 | - private static Collection<String> getPrimitiveInsertStatements() { | |
| 297 | - ArrayList<String> insertStatements = new ArrayList<String>(); | |
| 298 | - | |
| 299 | - for (DataType dataType : SAMPLE_DATA.keySet()) { | |
| 300 | - String value = helperStringifiedData(dataType); | |
| 301 | - insertStatements.add(String.format(PRIMITIVE_INSERT_FORMAT, dataType, value)); | |
| 302 | - } | |
| 104 | + Row row = session.execute(table.selectStatement).one(); | |
| 105 | + Object queriedValue = table.testColumnType.deserialize(row.getBytesUnsafe("v"), protocolVersion); | |
| 303 | 106 | |
| 304 | - return insertStatements; | |
| 305 | - } | |
| 107 | + assertThat(queriedValue) | |
| 108 | + .as("Test failure on %s statement with table:%n%s;%n" + | |
| 109 | + "insert statement:%n%s;%n", | |
| 110 | + statementType, | |
| 111 | + table.createStatement, | |
| 112 | + table.insertStatement) | |
| 113 | + .isEqualTo(table.sampleValue); | |
| 306 | 114 | |
| 307 | - /** | |
| 308 | - * Generates the select statements that will be used in testing | |
| 309 | - */ | |
| 310 | - private static HashMap<DataType, String> getPrimitiveSelectStatements() { | |
| 311 | - HashMap<DataType, String> selectStatements = new HashMap<DataType, String>(); | |
| 312 | - | |
| 313 | - for (DataType dataType : SAMPLE_DATA.keySet()) { | |
| 314 | - selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, dataType)); | |
| 115 | + session.execute(table.truncateStatement); | |
| 315 | 116 | } |
| 316 | - | |
| 317 | - return selectStatements; | |
| 318 | - } | |
| 319 | - | |
| 320 | - /** | |
| 321 | - * Helper method to generate table names in the form of: | |
| 322 | - * DataType_TypeArgument[_TypeArgument] | |
| 323 | - */ | |
| 324 | - private static String helperGenerateTableName(DataType dataType) { | |
| 325 | - String tableName = dataType.getName().toString(); | |
| 326 | - for (DataType typeArgument : dataType.getTypeArguments()) | |
| 327 | - tableName += "_" + typeArgument; | |
| 328 | - | |
| 329 | - return tableName; | |
| 330 | 117 | } |
| 331 | 118 | |
| 332 | 119 | /** |
| 333 | - * Generates the insert statements that will be used in testing | |
| 120 | + * Abstracts information about a table (corresponding to a given column type). | |
| 334 | 121 | */ |
| 335 | - @SuppressWarnings("unchecked") | |
| 336 | - private static Collection<String> getCollectionInsertStatements() { | |
| 337 | - ArrayList<String> insertStatements = new ArrayList<String>(); | |
| 338 | - | |
| 339 | - String tableName; | |
| 340 | - String key; | |
| 341 | - String value; | |
| 342 | - for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) { | |
| 343 | - HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType); | |
| 344 | - | |
| 345 | - // Create tableName in form of: DataType_TypeArgument[_TypeArgument] | |
| 346 | - tableName = helperGenerateTableName(dataType); | |
| 347 | - | |
| 348 | - if (dataType.getName() == DataType.Name.MAP) { | |
| 349 | - List<DataType> typeArgument = dataType.getTypeArguments(); | |
| 350 | - | |
| 351 | - key = helperStringifiedData(typeArgument.get(0)); | |
| 352 | - value = helperStringifiedData(typeArgument.get(1)); | |
| 353 | - | |
| 354 | - insertStatements.add(String.format(MAP_INSERT_FORMAT, tableName, key, value)); | |
| 355 | - } else if (dataType.getName() == DataType.Name.LIST) { | |
| 356 | - DataType typeArgument = sampleValueMap.keySet().iterator().next(); | |
| 357 | - key = helperStringifiedData(typeArgument); | |
| 358 | - | |
| 359 | - // Create the value to be a list of the same 5 elements | |
| 360 | - value = "["; | |
| 361 | - for (int i = 0; i < 5; i++) | |
| 362 | - value += key + ','; | |
| 363 | - value = value.substring(0, value.length() - 1) + ']'; | |
| 364 | - | |
| 365 | - insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value)); | |
| 366 | - } else { | |
| 367 | - DataType typeArgument = sampleValueMap.keySet().iterator().next(); | |
| 368 | - key = helperStringifiedData(typeArgument); | |
| 369 | - value = '{' + key + '}'; | |
| 370 | - | |
| 371 | - insertStatements.add(String.format(COLLECTION_INSERT_FORMAT, tableName, key, value)); | |
| 372 | - } | |
| 373 | - } | |
| 122 | + static class TestTable { | |
| 123 | + private static final AtomicInteger counter = new AtomicInteger(); | |
| 124 | + private String tableName = "date_type_test" + counter.incrementAndGet(); | |
| 374 | 125 | |
| 375 | - return insertStatements; | |
| 376 | - } | |
| 126 | + final DataType testColumnType; | |
| 127 | + final Object sampleValue; | |
| 377 | 128 | |
| 378 | - /** | |
| 379 | - * Generates the select statements that will be used in testing | |
| 380 | - */ | |
| 381 | - private static HashMap<DataType, String> getCollectionSelectStatements() { | |
| 382 | - HashMap<DataType, String> selectStatements = new HashMap<DataType, String>(); | |
| 383 | - | |
| 384 | - String tableName; | |
| 385 | - for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) { | |
| 386 | - tableName = helperGenerateTableName(dataType); | |
| 387 | - selectStatements.put(dataType, String.format(BASIC_SELECT_FORMAT, tableName)); | |
| 388 | - } | |
| 129 | + final String createStatement; | |
| 130 | + final String insertStatement = String.format("INSERT INTO %s (k, v) VALUES (1, ?)", tableName); | |
| 131 | + final String selectStatement = String.format("SELECT v FROM %s WHERE k = 1", tableName); | |
| 132 | + final String truncateStatement = String.format("TRUNCATE %s", tableName); | |
| 389 | 133 | |
| 390 | - return selectStatements; | |
| 391 | - } | |
| 134 | + final VersionNumber minCassandraVersion; | |
| 392 | 135 | |
| 393 | - /** | |
| 394 | - * Test simple statement inserts for all primitive data types | |
| 395 | - */ | |
| 396 | - public void primitiveInsertTest() throws Throwable { | |
| 397 | - ResultSet rs; | |
| 398 | - for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) { | |
| 399 | - rs = session.execute(execute_string); | |
| 400 | - assertTrue(rs.isExhausted()); | |
| 401 | - } | |
| 402 | - assertEquals(SAMPLE_DATA.size(), 14); | |
| 403 | - assertEquals(PRIMITIVE_INSERT_STATEMENTS.size(), SAMPLE_DATA.size()); | |
| 404 | - } | |
| 136 | + TestTable(DataType testColumnType, Object sampleValue, String minCassandraVersion) { | |
| 137 | + this.testColumnType = testColumnType; | |
| 138 | + this.sampleValue = sampleValue; | |
| 139 | + this.minCassandraVersion = VersionNumber.parse(minCassandraVersion); | |
| 405 | 140 | |
| 406 | - /** | |
| 407 | - * Validate simple statement selects for all primitive data types | |
| 408 | - */ | |
| 409 | - public void primitiveSelectTest() throws Throwable { | |
| 410 | - String execute_string; | |
| 411 | - Object value; | |
| 412 | - Row row; | |
| 413 | - for (DataType dataType : PRIMITIVE_SELECT_STATEMENTS.keySet()) { | |
| 414 | - execute_string = PRIMITIVE_SELECT_STATEMENTS.get(dataType); | |
| 415 | - row = session.execute(execute_string).one(); | |
| 416 | - | |
| 417 | - value = SAMPLE_DATA.get(dataType); | |
| 418 | - assertEquals(TestUtils.getValue(row, "k", dataType), value); | |
| 419 | - assertEquals(TestUtils.getValue(row, "v", dataType), value); | |
| 141 | + this.createStatement = String.format("CREATE TABLE %s (k int PRIMARY KEY, v %s)", tableName, testColumnType); | |
| 420 | 142 | } |
| 421 | - assertEquals(SAMPLE_DATA.size(), 14); | |
| 422 | - assertEquals(PRIMITIVE_SELECT_STATEMENTS.keySet().size(), SAMPLE_DATA.size()); | |
| 423 | 143 | } |
| 424 | 144 | |
| 425 | - /** | |
| 426 | - * Test simple statement inserts and selects for all primitive data types | |
| 427 | - */ | |
| 428 | - @Test(groups = "long") | |
| 429 | - public void primitiveTests() throws Throwable { | |
| 430 | - primitiveInsertTest(); | |
| 431 | - primitiveSelectTest(); | |
| 432 | - } | |
| 145 | + private static List<TestTable> allTables() { | |
| 146 | + List<TestTable> tables = Lists.newArrayList(); | |
| 433 | 147 | |
| 434 | - @Test(groups = "short") | |
| 435 | - @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2") | |
| 436 | - public void primitiveInsertWithValueTest() throws Throwable { | |
| 437 | - for (DataType dt : DataType.allPrimitiveTypes()) { | |
| 438 | - if (exclude(dt)) | |
| 439 | - continue; | |
| 148 | + tables.addAll(tablesWithPrimitives()); | |
| 149 | + tables.addAll(tablesWithCollectionsOfPrimitives()); | |
| 150 | + tables.addAll(tablesWithMapsOfPrimitives()); | |
| 151 | + tables.addAll(tablesWithNestedCollections()); | |
| 440 | 152 | |
| 441 | - session.execute(String.format(PRIMITIVE_INSERT_FORMAT, dt, "?"), SAMPLE_DATA.get(dt), SAMPLE_DATA.get(dt)); | |
| 442 | - } | |
| 443 | - // Kind of checking results (kind of because the schema used by this class make it ultra painful | |
| 444 | - // somehow to use a different partition for different tests, so that the insert done here actually | |
| 445 | - // conflict with the one in primitiveInsertTest. So all we check is that we don't write something | |
| 446 | - // horribly wrong, but if the inserts of this test where to do nothing, the following check might | |
| 447 | - // not work. We should fix the schema used by this class) | |
| 448 | - primitiveSelectTest(); | |
| 153 | + return ImmutableList.copyOf(tables); | |
| 449 | 154 | } |
| 450 | 155 | |
| 451 | - /** | |
| 452 | - * Test simple statement inserts for all collection data types | |
| 453 | - */ | |
| 454 | - public void collectionInsertTest() throws Throwable { | |
| 455 | - ResultSet rs; | |
| 456 | - for (String execute_string : COLLECTION_INSERT_STATEMENTS) { | |
| 457 | - rs = session.execute(execute_string); | |
| 458 | - assertTrue(rs.isExhausted()); | |
| 459 | - } | |
| 460 | - assertEquals(SAMPLE_COLLECTIONS.size(), 224); | |
| 461 | - assertEquals(COLLECTION_INSERT_STATEMENTS.size(), SAMPLE_COLLECTIONS.size()); | |
| 156 | + private static List<TestTable> tablesWithPrimitives() { | |
| 157 | + List<TestTable> tables = Lists.newArrayList(); | |
| 158 | + for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) | |
| 159 | + tables.add(new TestTable(entry.getKey(), entry.getValue(), "1.2.0")); | |
| 160 | + return tables; | |
| 462 | 161 | } |
| 463 | 162 | |
| 464 | - /** | |
| 465 | - * Test simple statement selects for all collection data types | |
| 466 | - */ | |
| 467 | - @SuppressWarnings("unchecked") | |
| 468 | - public void collectionSelectTest() throws Throwable { | |
| 469 | - HashMap<DataType, Object> sampleValueMap; | |
| 470 | - String execute_string; | |
| 471 | - DataType typeArgument1; | |
| 472 | - DataType typeArgument2; | |
| 473 | - Row row; | |
| 474 | - for (DataType dataType : COLLECTION_SELECT_STATEMENTS.keySet()) { | |
| 475 | - execute_string = COLLECTION_SELECT_STATEMENTS.get(dataType); | |
| 476 | - row = session.execute(execute_string).one(); | |
| 477 | - | |
| 478 | - sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType); | |
| 479 | - typeArgument1 = dataType.getTypeArguments().get(0); | |
| 480 | - if (dataType.getName() == DataType.Name.MAP) { | |
| 481 | - typeArgument2 = dataType.getTypeArguments().get(1); | |
| 482 | - | |
| 483 | - // Create a copy of the map that is being expected | |
| 484 | - HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument1); | |
| 485 | - Object mapKey = SAMPLE_DATA.get(sampleMap.keySet().iterator().next()); | |
| 486 | - Object mapValue = sampleMap.values().iterator().next(); | |
| 487 | - HashMap<Object, Object> expectedMap = new HashMap<Object, Object>(); | |
| 488 | - expectedMap.put(mapKey, mapValue); | |
| 489 | - | |
| 490 | - assertEquals(TestUtils.getValue(row, "k", typeArgument2), SAMPLE_DATA.get(typeArgument2)); | |
| 491 | - assertEquals(TestUtils.getValue(row, "v", dataType), expectedMap); | |
| 492 | - } else { | |
| 493 | - Object expectedValue = sampleValueMap.get(typeArgument1); | |
| 494 | - | |
| 495 | - assertEquals(TestUtils.getValue(row, "k", typeArgument1), SAMPLE_DATA.get(typeArgument1)); | |
| 496 | - assertEquals(TestUtils.getValue(row, "v", dataType), expectedValue); | |
| 497 | - } | |
| 498 | - } | |
| 499 | - assertEquals(SAMPLE_COLLECTIONS.size(), 224); | |
| 500 | - assertEquals(COLLECTION_SELECT_STATEMENTS.keySet().size(), SAMPLE_COLLECTIONS.size()); | |
| 501 | - } | |
| 163 | + private static List<TestTable> tablesWithCollectionsOfPrimitives() { | |
| 164 | + List<TestTable> tables = Lists.newArrayList(); | |
| 165 | + for (Map.Entry<DataType, Object> entry : PrimitiveTypeSamples.ALL.entrySet()) { | |
| 502 | 166 | |
| 503 | - /** | |
| 504 | - * Test simple statement inserts and selects for all collection data types | |
| 505 | - */ | |
| 506 | - @Test(groups = "long") | |
| 507 | - public void collectionTest() throws Throwable { | |
| 508 | - collectionInsertTest(); | |
| 509 | - collectionSelectTest(); | |
| 510 | - } | |
| 167 | + DataType elementType = entry.getKey(); | |
| 168 | + Object elementSample = entry.getValue(); | |
| 511 | 169 | |
| 512 | - /** | |
| 513 | - * Prints the table definitions that will be used in testing | |
| 514 | - * (for exporting purposes) | |
| 515 | - */ | |
| 516 | - @Test(groups = "doc") | |
| 517 | - public void printTableDefinitions() { | |
| 518 | - String objective = "Table Definitions"; | |
| 519 | - System.out.println(String.format("Printing %s...", objective)); | |
| 520 | - | |
| 521 | - // Prints the full list of table definitions | |
| 522 | - for (String definition : getTableDefinitions()) { | |
| 523 | - System.out.println(definition); | |
| 170 | + tables.add(new TestTable(DataType.list(elementType), Lists.newArrayList(elementSample, elementSample), "1.2.0")); | |
| 171 | + tables.add(new TestTable(DataType.set(elementType), Sets.newHashSet(elementSample), "1.2.0")); | |
| 524 | 172 | } |
| 525 | - | |
| 526 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 173 | + return tables; | |
| 527 | 174 | } |
| 528 | 175 | |
| 529 | - /** | |
| 530 | - * Prints the sample data that will be used in testing | |
| 531 | - * (for exporting purposes) | |
| 532 | - */ | |
| 533 | - @Test(groups = "doc") | |
| 534 | - public void printSampleData() { | |
| 535 | - String objective = "Sample Data"; | |
| 536 | - System.out.println(String.format("Printing %s...", objective)); | |
| 537 | - | |
| 538 | - for (DataType dataType : SAMPLE_DATA.keySet()) { | |
| 539 | - Object sampleValue = SAMPLE_DATA.get(dataType); | |
| 540 | - System.out.println(String.format("%1$-10s %2$s", dataType, sampleValue)); | |
| 541 | - } | |
| 542 | - | |
| 543 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 544 | - } | |
| 176 | + private static List<TestTable> tablesWithMapsOfPrimitives() { | |
| 177 | + List<TestTable> tables = Lists.newArrayList(); | |
| 178 | + for (Map.Entry<DataType, Object> keyEntry : PrimitiveTypeSamples.ALL.entrySet()) { | |
| 179 | + DataType keyType = keyEntry.getKey(); | |
| 180 | + Object keySample = keyEntry.getValue(); | |
| 181 | + for (Map.Entry<DataType, Object> valueEntry : PrimitiveTypeSamples.ALL.entrySet()) { | |
| 182 | + DataType valueType = valueEntry.getKey(); | |
| 183 | + Object valueSample = valueEntry.getValue(); | |
| 545 | 184 | |
| 546 | - /** | |
| 547 | - * Prints the sample collections that will be used in testing | |
| 548 | - * (for exporting purposes) | |
| 549 | - */ | |
| 550 | - @Test(groups = "doc") | |
| 551 | - @SuppressWarnings("unchecked") | |
| 552 | - public void printSampleCollections() { | |
| 553 | - String objective = "Sample Collections"; | |
| 554 | - System.out.println(String.format("Printing %s...", objective)); | |
| 555 | - | |
| 556 | - for (DataType dataType : SAMPLE_COLLECTIONS.keySet()) { | |
| 557 | - HashMap<DataType, Object> sampleValueMap = (HashMap<DataType, Object>) SAMPLE_COLLECTIONS.get(dataType); | |
| 558 | - | |
| 559 | - if (dataType.getName() == DataType.Name.MAP) { | |
| 560 | - DataType typeArgument = sampleValueMap.keySet().iterator().next(); | |
| 561 | - HashMap<DataType, Object> sampleMap = (HashMap<DataType, Object>) sampleValueMap.get(typeArgument); | |
| 562 | - | |
| 563 | - Object mapKey = SAMPLE_DATA.get(typeArgument); | |
| 564 | - Object mapValue = sampleMap.get(typeArgument); | |
| 565 | - System.out.println(String.format("%1$-30s {%2$s : %3$s}", dataType, mapKey, mapValue)); | |
| 566 | - } else { | |
| 567 | - DataType typeArgument = sampleValueMap.keySet().iterator().next(); | |
| 568 | - Object sampleValue = sampleValueMap.get(typeArgument); | |
| 569 | - | |
| 570 | - System.out.println(String.format("%1$-30s %2$s", dataType, sampleValue)); | |
| 185 | + tables.add(new TestTable(DataType.map(keyType, valueType), | |
| 186 | + ImmutableMap.builder().put(keySample, valueSample).build(), | |
| 187 | + "1.2.0")); | |
| 571 | 188 | } |
| 572 | 189 | } |
| 573 | - | |
| 574 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 190 | + return tables; | |
| 575 | 191 | } |
| 576 | 192 | |
| 577 | - /** | |
| 578 | - * Prints the simple insert statements that will be used in testing | |
| 579 | - * (for exporting purposes) | |
| 580 | - */ | |
| 581 | - @Test(groups = "doc") | |
| 582 | - public void printPrimitiveInsertStatements() { | |
| 583 | - String objective = "Primitive Insert Statements"; | |
| 584 | - System.out.println(String.format("Printing %s...", objective)); | |
| 585 | - | |
| 586 | - for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) { | |
| 587 | - System.out.println(execute_string); | |
| 588 | - } | |
| 193 | + private static Collection<? extends TestTable> tablesWithNestedCollections() { | |
| 194 | + List<TestTable> tables = Lists.newArrayList(); | |
| 589 | 195 | |
| 590 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 591 | - } | |
| 196 | + // To avoid combinatorial explosion, only use int as the primitive type, and two levels of nesting. | |
| 197 | + // This yields collections like list<frozen<map<int, int>>, map<frozen<set<int>>, frozen<list<int>>>, etc. | |
| 592 | 198 | |
| 593 | - /** | |
| 594 | - * Prints the simple select statements that will be used in testing | |
| 595 | - * (for exporting purposes) | |
| 596 | - */ | |
| 597 | - @Test(groups = "doc") | |
| 598 | - public void printPrimitiveSelectStatements() { | |
| 599 | - String objective = "Primitive Select Statements"; | |
| 600 | - System.out.println(String.format("Printing %s...", objective)); | |
| 601 | - | |
| 602 | - for (String execute_string : PRIMITIVE_SELECT_STATEMENTS.values()) { | |
| 603 | - System.out.println(execute_string); | |
| 604 | - } | |
| 199 | + // Types and samples for the inner collections like frozen<list<int>> | |
| 200 | + Map<DataType, Object> childCollectionSamples = ImmutableMap.<DataType, Object>builder() | |
| 201 | + .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1)) | |
| 202 | + .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2)) | |
| 203 | + .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build()) | |
| 204 | + .build(); | |
| 605 | 205 | |
| 606 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 607 | - } | |
| 206 | + for (Map.Entry<DataType, Object> entry : childCollectionSamples.entrySet()) { | |
| 207 | + DataType elementType = entry.getKey(); | |
| 208 | + Object elementSample = entry.getValue(); | |
| 608 | 209 | |
| 609 | - /** | |
| 610 | - * Prints the simple insert statements that will be used in testing | |
| 611 | - * (for exporting purposes) | |
| 612 | - */ | |
| 613 | - @Test(groups = "doc") | |
| 614 | - public void printCollectionInsertStatements() { | |
| 615 | - String objective = "Collection Insert Statements"; | |
| 616 | - System.out.println(String.format("Printing %s...", objective)); | |
| 617 | - | |
| 618 | - for (String execute_string : COLLECTION_INSERT_STATEMENTS) { | |
| 619 | - System.out.println(execute_string); | |
| 620 | - } | |
| 210 | + tables.add(new TestTable(DataType.list(elementType), Lists.newArrayList(elementSample, elementSample), "2.1.3")); | |
| 211 | + tables.add(new TestTable(DataType.set(elementType), Sets.newHashSet(elementSample), "2.1.3")); | |
| 621 | 212 | |
| 622 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 623 | - } | |
| 213 | + for (Map.Entry<DataType, Object> valueEntry : childCollectionSamples.entrySet()) { | |
| 214 | + DataType valueType = valueEntry.getKey(); | |
| 215 | + Object valueSample = valueEntry.getValue(); | |
| 624 | 216 | |
| 625 | - /** | |
| 626 | - * Prints the simple insert statements that will be used in testing | |
| 627 | - * (for exporting purposes) | |
| 628 | - */ | |
| 629 | - @Test(groups = "doc") | |
| 630 | - public void printCollectionSelectStatements() { | |
| 631 | - String objective = "Collection Select Statements"; | |
| 632 | - System.out.println(String.format("Printing %s...", objective)); | |
| 633 | - | |
| 634 | - for (String execute_string : COLLECTION_SELECT_STATEMENTS.values()) { | |
| 635 | - System.out.println(execute_string); | |
| 217 | + tables.add(new TestTable(DataType.map(elementType, valueType), | |
| 218 | + ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3")); | |
| 219 | + } | |
| 636 | 220 | } |
| 637 | - | |
| 638 | - System.out.println(String.format("\nEnd of %s\n\n", objective)); | |
| 221 | + return tables; | |
| 639 | 222 | } |
| 640 | 223 | } |
| 641 | - |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +25 −2
| @@ -19,15 +19,19 @@ | ||
| 19 | 19 | import java.math.BigInteger; |
| 20 | 20 | import java.net.InetAddress; |
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | -import java.text.SimpleDateFormat; | |
| 23 | 22 | import java.util.*; |
| 24 | 23 | |
| 24 | +import com.google.common.reflect.TypeToken; | |
| 25 | 25 | import org.testng.annotations.Test; |
| 26 | -import static org.testng.Assert.*; | |
| 26 | + | |
| 27 | +import static org.testng.Assert.assertEquals; | |
| 28 | +import static org.testng.Assert.fail; | |
| 27 | 29 | |
| 28 | 30 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 29 | 31 | import com.datastax.driver.core.utils.Bytes; |
| 30 | 32 | |
| 33 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 34 | + | |
| 31 | 35 | /** |
| 32 | 36 | * DataType simple unit tests. |
| 33 | 37 | */ |
| @@ -246,4 +250,23 @@ | ||
| 246 | 250 | fail("This should not have worked"); |
| 247 | 251 | } catch (InvalidTypeException e) { /* That's what we want */ } |
| 248 | 252 | } |
| 253 | + | |
| 254 | + @Test(groups = "unit") | |
| 255 | + public void should_check_which_java_type_it_can_be_deserialized_to() { | |
| 256 | + assertThat(DataType.cint()) | |
| 257 | + .canBeDeserializedAs(TypeToken.of(Integer.class)) | |
| 258 | + .canBeDeserializedAs(TypeToken.of(Number.class)) | |
| 259 | + .cannotBeDeserializedAs(TypeToken.of(String.class)); | |
| 260 | + | |
| 261 | + assertThat(DataType.list(DataType.cint())) | |
| 262 | + .canBeDeserializedAs(new TypeToken<List<Integer>>(){}) | |
| 263 | + .canBeDeserializedAs(new TypeToken<Collection<Integer>>(){}) | |
| 264 | + .cannotBeDeserializedAs(new TypeToken<Set<Integer>>(){}) | |
| 265 | + .cannotBeDeserializedAs(new TypeToken<List<String>>(){}); | |
| 266 | + | |
| 267 | + assertThat(DataType.map(DataType.cint(), DataType.frozenList(DataType.text()))) | |
| 268 | + .canBeDeserializedAs(new TypeToken<Map<Integer, List<String>>>(){}) | |
| 269 | + .canBeDeserializedAs(new TypeToken<Map<Number, Collection<String>>>(){}) | |
| 270 | + .cannotBeDeserializedAs(new TypeToken<Map<Integer, Collection<Integer>>>(){}); | |
| 271 | + } | |
| 249 | 272 | } |
added driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 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.math.BigDecimal; | |
| 19 | +import java.math.BigInteger; | |
| 20 | +import java.net.InetAddress; | |
| 21 | +import java.net.UnknownHostException; | |
| 22 | +import java.util.Date; | |
| 23 | +import java.util.List; | |
| 24 | +import java.util.Map; | |
| 25 | +import java.util.UUID; | |
| 26 | + | |
| 27 | +import com.google.common.collect.ImmutableMap; | |
| 28 | +import com.google.common.collect.Lists; | |
| 29 | + | |
| 30 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 31 | + | |
| 32 | +import com.datastax.driver.core.utils.Bytes; | |
| 33 | + | |
| 34 | +/** | |
| 35 | + * This class provides sample values for each primitive data type. | |
| 36 | + * | |
| 37 | + * These values have no particular meaning, the goal is just to have an instance that can be used in automated tests. | |
| 38 | + */ | |
| 39 | +public class PrimitiveTypeSamples { | |
| 40 | + | |
| 41 | + public static final Map<DataType, Object> ALL = generateAll(); | |
| 42 | + | |
| 43 | + private static Map<DataType, Object> generateAll() { | |
| 44 | + try { | |
| 45 | + ImmutableMap<DataType, Object> result = ImmutableMap.<DataType, Object>builder() | |
| 46 | + .put(DataType.ascii(), "ascii") | |
| 47 | + .put(DataType.bigint(), Long.MAX_VALUE) | |
| 48 | + .put(DataType.blob(), Bytes.fromHexString("0xCAFE")) | |
| 49 | + .put(DataType.cboolean(), Boolean.TRUE) | |
| 50 | + .put(DataType.decimal(), new BigDecimal("12.3E+7")) | |
| 51 | + .put(DataType.cdouble(), Double.MAX_VALUE) | |
| 52 | + .put(DataType.cfloat(), Float.MAX_VALUE) | |
| 53 | + .put(DataType.inet(), InetAddress.getByName("123.123.123.123")) | |
| 54 | + .put(DataType.cint(), Integer.MAX_VALUE) | |
| 55 | + .put(DataType.text(), "text") | |
| 56 | + .put(DataType.timestamp(), new Date(872835240000L)) | |
| 57 | + .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66")) | |
| 58 | + .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00")) | |
| 59 | + .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000")) | |
| 60 | + .build(); | |
| 61 | + | |
| 62 | + // Check that we cover all types (except counter) | |
| 63 | + List<DataType> tmp = Lists.newArrayList(DataType.allPrimitiveTypes()); | |
| 64 | + tmp.removeAll(result.keySet()); | |
| 65 | + assertThat(tmp) | |
| 66 | + .as("new datatype not covered in test") | |
| 67 | + .containsOnly(DataType.counter()); | |
| 68 | + | |
| 69 | + return result; | |
| 70 | + } catch (UnknownHostException e) { | |
| 71 | + throw new AssertionError(e); | |
| 72 | + } | |
| 73 | + } | |
| 74 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +2 −2
| @@ -71,7 +71,7 @@ | ||
| 71 | 71 | session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); |
| 72 | 72 | |
| 73 | 73 | for (Metadata m : metadatas) |
| 74 | - assertThat(m.getKeyspace(keyspace).getUserType("type1")) | |
| 74 | + assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) | |
| 75 | 75 | .isNotNull(); |
| 76 | 76 | } |
| 77 | 77 | |
| @@ -93,7 +93,7 @@ | ||
| 93 | 93 | session.execute(String.format("DROP TYPE %s.type1", keyspace)); |
| 94 | 94 | |
| 95 | 95 | for (Metadata m : metadatas) |
| 96 | - assertThat(m.getKeyspace(keyspace).getUserType("type1")) | |
| 96 | + assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) | |
| 97 | 97 | .isNull(); |
| 98 | 98 | } |
| 99 | 99 |
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +13 −46
| @@ -15,18 +15,19 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 19 | 18 | import java.nio.ByteBuffer; |
| 19 | +import java.util.*; | |
| 20 | 20 | |
| 21 | +import com.beust.jcommander.internal.Lists; | |
| 21 | 22 | import com.google.common.base.Joiner; |
| 22 | 23 | import org.testng.annotations.Test; |
| 23 | 24 | |
| 24 | -import static com.datastax.driver.core.DataTypeIntegrationTest.getSampleData; | |
| 25 | -import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE; | |
| 26 | -import static com.datastax.driver.core.TestUtils.versionCheck; | |
| 27 | 25 | import static org.testng.Assert.assertEquals; |
| 28 | 26 | import static org.testng.Assert.fail; |
| 29 | 27 | |
| 28 | +import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE; | |
| 29 | +import static com.datastax.driver.core.TestUtils.versionCheck; | |
| 30 | + | |
| 30 | 31 | public class TupleTest extends CCMBridge.PerClassSingleNodeCluster { |
| 31 | 32 | |
| 32 | 33 | @Override |
| @@ -215,16 +216,7 @@ | ||
| 215 | 216 | @Test(groups = "short") |
| 216 | 217 | public void tupleSubtypesTest() throws Exception { |
| 217 | 218 | |
| 218 | - // hold onto constants | |
| 219 | - ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); | |
| 220 | - for (DataType dt : DataType.allPrimitiveTypes()) { | |
| 221 | - // skip counter types since counters are not allowed inside tuples | |
| 222 | - if (dt == DataType.counter()) | |
| 223 | - continue; | |
| 224 | - | |
| 225 | - DATA_TYPE_PRIMITIVES.add(dt); | |
| 226 | - } | |
| 227 | - HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); | |
| 219 | + List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet()); | |
| 228 | 220 | |
| 229 | 221 | try { |
| 230 | 222 | session.execute("CREATE KEYSPACE test_tuple_subtypes " + |
| @@ -249,8 +241,8 @@ | ||
| 249 | 241 | for (int j = 0; j < i; ++j) { |
| 250 | 242 | dataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); |
| 251 | 243 | completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); |
| 252 | - createdValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 253 | - completeValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 244 | + createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 245 | + completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 254 | 246 | } |
| 255 | 247 | |
| 256 | 248 | // complete portion of the arrays needed for trailing nulls |
| @@ -290,19 +282,7 @@ | ||
| 290 | 282 | @Test(groups = "short") |
| 291 | 283 | public void tupleNonPrimitiveSubTypesTest() throws Exception { |
| 292 | 284 | |
| 293 | - // hold onto constants | |
| 294 | - ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); | |
| 295 | - for (DataType dt : DataType.allPrimitiveTypes()) { | |
| 296 | - // skip counter types since counters are not allowed inside tuples | |
| 297 | - if (dt == DataType.counter()) | |
| 298 | - continue; | |
| 299 | - | |
| 300 | - DATA_TYPE_PRIMITIVES.add(dt); | |
| 301 | - } | |
| 302 | - ArrayList<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = new ArrayList<DataType.Name>(Arrays.asList(DataType.Name.MAP, | |
| 303 | - DataType.Name.SET, | |
| 304 | - DataType.Name.LIST)); | |
| 305 | - HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); | |
| 285 | + List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet()); | |
| 306 | 286 | |
| 307 | 287 | try { |
| 308 | 288 | session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " + |
| @@ -323,9 +303,7 @@ | ||
| 323 | 303 | |
| 324 | 304 | // create map values |
| 325 | 305 | for (DataType datatype : DATA_TYPE_PRIMITIVES) { |
| 326 | - DataType dataType1 = datatype; | |
| 327 | - DataType dataType2 = datatype; | |
| 328 | - values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), dataType1, dataType2)); | |
| 306 | + values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype)); | |
| 329 | 307 | } |
| 330 | 308 | |
| 331 | 309 | // create table |
| @@ -340,7 +318,7 @@ | ||
| 340 | 318 | ArrayList<Object> createdValues = new ArrayList<Object>(); |
| 341 | 319 | |
| 342 | 320 | dataTypes.add(DataType.list(datatype)); |
| 343 | - createdValues.add(Arrays.asList(SAMPLE_DATA.get(datatype))); | |
| 321 | + createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))); | |
| 344 | 322 | |
| 345 | 323 | TupleType t = new TupleType(dataTypes); |
| 346 | 324 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| @@ -363,7 +341,7 @@ | ||
| 363 | 341 | ArrayList<Object> createdValues = new ArrayList<Object>(); |
| 364 | 342 | |
| 365 | 343 | dataTypes.add(DataType.set(datatype)); |
| 366 | - createdValues.add(new HashSet<Object>(Arrays.asList(SAMPLE_DATA.get(datatype)))); | |
| 344 | + createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)))); | |
| 367 | 345 | |
| 368 | 346 | TupleType t = new TupleType(dataTypes); |
| 369 | 347 | TupleValue createdTuple = t.newValue(createdValues.toArray()); |
| @@ -386,7 +364,7 @@ | ||
| 386 | 364 | ArrayList<Object> createdValues = new ArrayList<Object>(); |
| 387 | 365 | |
| 388 | 366 | HashMap<Object, Object> hm = new HashMap<Object, Object>(); |
| 389 | - hm.put(SAMPLE_DATA.get(datatype), SAMPLE_DATA.get(datatype)); | |
| 367 | + hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype)); | |
| 390 | 368 | |
| 391 | 369 | dataTypes.add(DataType.map(datatype, datatype)); |
| 392 | 370 | createdValues.add(hm); |
| @@ -447,17 +425,6 @@ | ||
| 447 | 425 | @Test(groups = "short") |
| 448 | 426 | public void nestedTuplesTest() throws Exception { |
| 449 | 427 | |
| 450 | - // hold onto constants | |
| 451 | - ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); | |
| 452 | - for (DataType dt : DataType.allPrimitiveTypes()) { | |
| 453 | - // skip counter types since counters are not allowed inside tuples | |
| 454 | - if (dt == DataType.counter()) | |
| 455 | - continue; | |
| 456 | - | |
| 457 | - DATA_TYPE_PRIMITIVES.add(dt); | |
| 458 | - } | |
| 459 | - HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); | |
| 460 | - | |
| 461 | 428 | try { |
| 462 | 429 | session.execute("CREATE KEYSPACE test_nested_tuples " + |
| 463 | 430 | "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); |
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +9 −8
| @@ -22,9 +22,12 @@ | ||
| 22 | 22 | import java.nio.ByteBuffer; |
| 23 | 23 | import java.util.*; |
| 24 | 24 | |
| 25 | +import com.google.common.collect.ImmutableMap; | |
| 25 | 26 | import com.google.common.collect.ImmutableSet; |
| 26 | 27 | import com.google.common.base.Joiner; |
| 27 | 28 | |
| 29 | +import com.google.common.collect.Lists; | |
| 30 | +import com.google.common.collect.Sets; | |
| 28 | 31 | import org.testng.annotations.Test; |
| 29 | 32 | import static org.testng.Assert.assertEquals; |
| 30 | 33 | |
| @@ -38,8 +41,6 @@ | ||
| 38 | 41 | private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = |
| 39 | 42 | new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE)); |
| 40 | 43 | |
| 41 | - private final static HashMap<DataType, Object> SAMPLE_DATA = DataTypeIntegrationTest.getSampleData(); | |
| 42 | - | |
| 43 | 44 | @Override |
| 44 | 45 | protected Collection<String> getTableDefinitions() { |
| 45 | 46 | versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0"); |
| @@ -242,7 +243,7 @@ | ||
| 242 | 243 | for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) { |
| 243 | 244 | DataType dataType = DATA_TYPE_PRIMITIVES.get(i); |
| 244 | 245 | String index = Character.toString((char) (startIndex + i)); |
| 245 | - Object sampleData = SAMPLE_DATA.get(dataType); | |
| 246 | + Object sampleData = PrimitiveTypeSamples.ALL.get(dataType); | |
| 246 | 247 | |
| 247 | 248 | switch (dataType.getName()) { |
| 248 | 249 | case ASCII: |
| @@ -365,19 +366,19 @@ | ||
| 365 | 366 | DataType dataType = DATA_TYPE_PRIMITIVES.get(j); |
| 366 | 367 | |
| 367 | 368 | String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j)); |
| 368 | - Object sample = DataTypeIntegrationTest.getCollectionSample(name, dataType); | |
| 369 | + Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType); | |
| 369 | 370 | switch(name) { |
| 370 | 371 | case LIST: |
| 371 | - alldatatypes.setList(index, (ArrayList<DataType>) sample); | |
| 372 | + alldatatypes.setList(index, Lists.newArrayList(sampleElement)); | |
| 372 | 373 | break; |
| 373 | 374 | case SET: |
| 374 | - alldatatypes.setSet(index, (Set<DataType>) sample); | |
| 375 | + alldatatypes.setSet(index, Sets.newHashSet(sampleElement)); | |
| 375 | 376 | break; |
| 376 | 377 | case MAP: |
| 377 | - alldatatypes.setMap(index, (HashMap<DataType, DataType>) sample); | |
| 378 | + alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement)); | |
| 378 | 379 | break; |
| 379 | 380 | case TUPLE: |
| 380 | - alldatatypes.setTupleValue(index, (TupleValue) sample); | |
| 381 | + alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement)); | |
| 381 | 382 | } |
| 382 | 383 | } |
| 383 | 384 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +21 −1
| @@ -21,10 +21,12 @@ | ||
| 21 | 21 | import java.util.Date; |
| 22 | 22 | import java.util.List; |
| 23 | 23 | |
| 24 | +import com.google.common.collect.ImmutableList; | |
| 24 | 25 | import org.testng.annotations.Test; |
| 25 | 26 | |
| 26 | 27 | import com.datastax.driver.core.*; |
| 27 | 28 | |
| 29 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 28 | 30 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 29 | 31 | |
| 30 | 32 | import static org.testng.Assert.*; |
| @@ -38,7 +40,7 @@ | ||
| 38 | 40 | return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1), |
| 39 | 41 | "CREATE TABLE dateTest (t timestamp PRIMARY KEY)", |
| 40 | 42 | "CREATE TYPE udt (i int, a inet)", |
| 41 | - "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>)"); | |
| 43 | + "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>)"); | |
| 42 | 44 | } |
| 43 | 45 | |
| 44 | 46 | @Test(groups = "short") |
| @@ -126,4 +128,22 @@ | ||
| 126 | 128 | Row r1 = rows.get(0); |
| 127 | 129 | assertEquals("127.0.0.1", r1.getUDTValue("t").getInet("a").getHostAddress()); |
| 128 | 130 | } |
| 131 | + | |
| 132 | + @Test(groups = "short") | |
| 133 | + public void should_handle_collections_of_UDT() throws Exception { | |
| 134 | + UserType udtType = cluster.getMetadata().getKeyspace("ks").getUserType("udt"); | |
| 135 | + UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost")); | |
| 136 | + | |
| 137 | + Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue)); | |
| 138 | + assertThat(insert.toString()).isEqualTo("INSERT INTO udtTest(k,l) VALUES (1,[{i:2, a:'127.0.0.1'}]);"); | |
| 139 | + | |
| 140 | + session.execute(insert); | |
| 141 | + | |
| 142 | + List<Row> rows = session.execute(select().from("udtTest").where(eq("k", 1))).all(); | |
| 143 | + | |
| 144 | + assertThat(rows.size()).isEqualTo(1); | |
| 145 | + | |
| 146 | + Row r1 = rows.get(0); | |
| 147 | + assertThat(r1.getList("l", UDTValue.class).get(0).getInet("a").getHostAddress()).isEqualTo("127.0.0.1"); | |
| 148 | + } | |
| 129 | 149 | } |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +47 −2
| @@ -20,13 +20,19 @@ | ||
| 20 | 20 | import java.net.InetAddress; |
| 21 | 21 | import java.util.*; |
| 22 | 22 | |
| 23 | +import com.google.common.collect.ImmutableList; | |
| 24 | +import com.google.common.collect.ImmutableMap; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 26 | + | |
| 27 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 24 | 28 | import static org.testng.Assert.*; |
| 25 | 29 | |
| 26 | 30 | import com.datastax.driver.core.*; |
| 27 | 31 | import com.datastax.driver.core.querybuilder.Delete.Where; |
| 28 | 32 | import com.datastax.driver.core.utils.Bytes; |
| 33 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 29 | 34 | |
| 35 | +import static com.datastax.driver.core.DataType.cint; | |
| 30 | 36 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 31 | 37 | |
| 32 | 38 | public class QueryBuilderTest { |
| @@ -211,7 +217,7 @@ | ||
| 211 | 217 | assertEquals(insert.toString(), query); |
| 212 | 218 | |
| 213 | 219 | query = "INSERT INTO foo(k,x) VALUES (0,(1));"; |
| 214 | - insert = insertInto("foo").value("k", 0).value("x", TupleType.of(DataType.cint()).newValue(1)); | |
| 220 | + insert = insertInto("foo").value("k", 0).value("x", TupleType.of(cint()).newValue(1)); | |
| 215 | 221 | assertEquals(insert.toString(), query); |
| 216 | 222 | |
| 217 | 223 | // UDT: see QueryBuilderExecutionTest |
| @@ -562,7 +568,11 @@ | ||
| 562 | 568 | assertEquals(insert.toString(), query); |
| 563 | 569 | |
| 564 | 570 | query = "INSERT INTO foo(a,b) VALUES ({'2''} space','3','4'},3.4) USING TTL 24 AND TIMESTAMP 42;"; |
| 565 | - insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<String>(){{ add("2'} space"); add("3"); add("4"); }}, 3.4 }).using(ttl(24)).and(timestamp(42)); | |
| 571 | + insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<String>() {{ | |
| 572 | + add("2'} space"); | |
| 573 | + add("3"); | |
| 574 | + add("4"); | |
| 575 | + }}, 3.4 }).using(ttl(24)).and(timestamp(42)); | |
| 566 | 576 | assertEquals(insert.toString(), query); |
| 567 | 577 | } |
| 568 | 578 | |
| @@ -718,4 +728,39 @@ | ||
| 718 | 728 | // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage). |
| 719 | 729 | statement.getValues(ProtocolVersion.V3); |
| 720 | 730 | } |
| 731 | + | |
| 732 | + @Test(groups = "unit") | |
| 733 | + public void should_handle_collections_of_tuples() { | |
| 734 | + String query; | |
| 735 | + Statement statement; | |
| 736 | + | |
| 737 | + query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;"; | |
| 738 | + List<TupleValue> list = ImmutableList.of(TupleType.of(cint(), cint()).newValue(1, 2)); | |
| 739 | + statement = update("foo").with(set("l", list)).where(eq("k", 1)); | |
| 740 | + assertThat(statement.toString()).isEqualTo(query); | |
| 741 | + } | |
| 742 | + | |
| 743 | + @Test(groups = "unit") | |
| 744 | + @CassandraVersion(major = 2.1, minor = 3) | |
| 745 | + public void should_handle_nested_collections() { | |
| 746 | + String query; | |
| 747 | + Statement statement; | |
| 748 | + | |
| 749 | + query = "UPDATE foo SET l=[[1],[2]] WHERE k=1;"; | |
| 750 | + ImmutableList<ImmutableList<Integer>> list = ImmutableList.of(ImmutableList.of(1), ImmutableList.of(2)); | |
| 751 | + statement = update("foo").with(set("l", list)).where(eq("k", 1)); | |
| 752 | + assertThat(statement.toString()).isEqualTo(query); | |
| 753 | + | |
| 754 | + query = "UPDATE foo SET m={1:[[1],[2]],2:[[1],[2]]} WHERE k=1;"; | |
| 755 | + statement = update("foo").with(set("m", ImmutableMap.of(1, list, 2, list))).where(eq("k", 1)); | |
| 756 | + assertThat(statement.toString()).isEqualTo(query); | |
| 757 | + | |
| 758 | + query = "UPDATE foo SET l=[[1]]+l WHERE k=1;"; | |
| 759 | + statement = update("foo").with(prepend("l", ImmutableList.of(1))).where(eq("k", 1)); | |
| 760 | + assertThat(statement.toString()).isEqualTo(query); | |
| 761 | + | |
| 762 | + query = "UPDATE foo SET l=[[1],[2]]+l WHERE k=1;"; | |
| 763 | + statement = update("foo").with(prependAll("l", list)).where(eq("k", 1)); | |
| 764 | + assertThat(statement.toString()).isEqualTo(query); | |
| 765 | + } | |
| 721 | 766 | } |
modified driver-mapping/pom.xml +7 −0
| @@ -55,6 +55,13 @@ | ||
| 55 | 55 | <scope>test</scope> |
| 56 | 56 | </dependency> |
| 57 | 57 | |
| 58 | + <dependency> | |
| 59 | + <groupId>org.mockito</groupId> | |
| 60 | + <artifactId>mockito-all</artifactId> | |
| 61 | + <version>1.10.8</version> | |
| 62 | + <scope>test</scope> | |
| 63 | + </dependency> | |
| 64 | + | |
| 58 | 65 | <dependency> |
| 59 | 66 | <groupId>org.ow2.asm</groupId> |
| 60 | 67 | <artifactId>asm-all</artifactId> |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +29 −46
| @@ -20,13 +20,7 @@ | ||
| 20 | 20 | import java.lang.reflect.Field; |
| 21 | 21 | import java.util.*; |
| 22 | 22 | |
| 23 | -import com.google.common.primitives.Primitives; | |
| 24 | - | |
| 25 | 23 | import com.datastax.driver.mapping.annotations.*; |
| 26 | -import com.google.common.collect.ImmutableSet; | |
| 27 | -import com.google.common.collect.ImmutableSet.Builder; | |
| 28 | - | |
| 29 | -import com.datastax.driver.core.DataType; | |
| 30 | 24 | |
| 31 | 25 | /** |
| 32 | 26 | * Various checks on mapping annotations. |
| @@ -36,22 +30,6 @@ | ||
| 36 | 30 | // The package containing the mapping annotations |
| 37 | 31 | private static final Package MAPPING_PACKAGE = Table.class.getPackage(); |
| 38 | 32 | |
| 39 | - // The Java types that should not be annotated with @Frozen. Any other type is supposed | |
| 40 | - // to map to a UDT or tuple. | |
| 41 | - private static final Set<Class<?>> EXPECTED_NON_FROZEN_CLASSES; | |
| 42 | - static { | |
| 43 | - Builder<Class<?>> builder = ImmutableSet.<Class<?>>builder(); | |
| 44 | - for (DataType type : DataType.allPrimitiveTypes()) { | |
| 45 | - builder.add(type.asJavaClass()); | |
| 46 | - builder.add(Primitives.unwrap(type.asJavaClass())); | |
| 47 | - } | |
| 48 | - builder.add(List.class); | |
| 49 | - builder.add(Set.class); | |
| 50 | - builder.add(Map.class); | |
| 51 | - | |
| 52 | - EXPECTED_NON_FROZEN_CLASSES = builder.build(); | |
| 53 | - } | |
| 54 | - | |
| 55 | 33 | /** |
| 56 | 34 | * Checks that a class is decorated with the given annotation, and return the annotation instance. |
| 57 | 35 | * Also validates that no other mapping annotation is present. |
| @@ -118,35 +96,39 @@ | ||
| 118 | 96 | |
| 119 | 97 | static void checkFrozenTypes(Field field) { |
| 120 | 98 | Type javaType = field.getGenericType(); |
| 121 | - CQLType cqlType = getCQLType(field); | |
| 122 | - checkFrozenTypes(javaType, cqlType); | |
| 99 | + DeclaredFrozenType declaredFrozenType = getDeclaredFrozenType(field); | |
| 100 | + checkFrozenTypes(javaType, declaredFrozenType); | |
| 123 | 101 | } |
| 124 | 102 | |
| 125 | - // Builds a CQLType hierarchy based on the @Frozen* annotations on a field. | |
| 126 | - private static CQLType getCQLType(Field field) { | |
| 103 | + // Builds a DeclaredFrozenType hierarchy based on the @Frozen* annotations on a field. | |
| 104 | + private static DeclaredFrozenType getDeclaredFrozenType(Field field) { | |
| 127 | 105 | Frozen frozen = field.getAnnotation(Frozen.class); |
| 128 | 106 | if (frozen != null) |
| 129 | - return CQLType.parse(frozen.value()); | |
| 107 | + return DeclaredFrozenType.parse(frozen.value()); | |
| 130 | 108 | |
| 131 | 109 | boolean frozenKey = field.getAnnotation(FrozenKey.class) != null; |
| 132 | 110 | boolean frozenValue = field.getAnnotation(FrozenValue.class) != null; |
| 133 | 111 | if (frozenKey && frozenValue) |
| 134 | - return CQLType.FROZEN_MAP_KEY_AND_VALUE; | |
| 112 | + return DeclaredFrozenType.FROZEN_MAP_KEY_AND_VALUE; | |
| 135 | 113 | else if (frozenKey) |
| 136 | - return CQLType.FROZEN_MAP_KEY; | |
| 114 | + return DeclaredFrozenType.FROZEN_MAP_KEY; | |
| 137 | 115 | else if (frozenValue && field.getType().equals(Map.class)) |
| 138 | - return CQLType.FROZEN_MAP_VALUE; | |
| 116 | + return DeclaredFrozenType.FROZEN_MAP_VALUE; | |
| 139 | 117 | else if (frozenValue) |
| 140 | - return CQLType.FROZEN_ELEMENT; | |
| 118 | + return DeclaredFrozenType.FROZEN_ELEMENT; | |
| 141 | 119 | else |
| 142 | - return CQLType.UNFROZEN_SIMPLE; | |
| 120 | + return DeclaredFrozenType.UNFROZEN_SIMPLE; | |
| 143 | 121 | } |
| 144 | 122 | |
| 145 | 123 | // Traverses the Java type and CQLType hierarchies in parallel, to ensure that all |
| 146 | - // Java types mapping to UDTs and tuples are marked as frozen in the CQLType. | |
| 124 | + // Java types mapping to UDTs, tuples and nested collections are marked as frozen in the CQLType. | |
| 147 | 125 | // We accept that parts of the CQLType be null, in which case the matching parts |
| 148 | 126 | // in the Java type will be considered as not frozen. |
| 149 | - private static void checkFrozenTypes(Type javaType, CQLType cqlType) { | |
| 127 | + private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType) { | |
| 128 | + checkFrozenTypes(javaType, declaredFrozenType, true); | |
| 129 | + } | |
| 130 | + | |
| 131 | + private static void checkFrozenTypes(Type javaType, DeclaredFrozenType declaredFrozenType, boolean isRoot) { | |
| 150 | 132 | Class<?> javaClass; |
| 151 | 133 | Type[] childrenJavaTypes; |
| 152 | 134 | if (javaType instanceof Class<?>) { |
| @@ -159,26 +141,27 @@ | ||
| 159 | 141 | } else |
| 160 | 142 | throw new IllegalArgumentException("unexpected type: " + javaType); |
| 161 | 143 | |
| 162 | - boolean frozen = (cqlType != null && cqlType.frozen); | |
| 163 | - checkValidFrozen(javaClass, frozen); | |
| 144 | + boolean frozen = (declaredFrozenType != null && declaredFrozenType.frozen); | |
| 145 | + checkValidFrozen(javaClass, isRoot, frozen); | |
| 164 | 146 | |
| 165 | 147 | if (childrenJavaTypes != null) { |
| 166 | 148 | for (int i = 0; i < childrenJavaTypes.length; i++) { |
| 167 | 149 | Type childJavaType = childrenJavaTypes[i]; |
| 168 | - CQLType childCQLType = null; | |
| 169 | - if (cqlType != null && cqlType.subTypes != null && cqlType.subTypes.size() > i) | |
| 170 | - childCQLType = cqlType.subTypes.get(i); | |
| 171 | - checkFrozenTypes(childJavaType, childCQLType); | |
| 150 | + DeclaredFrozenType childDeclaredFrozenType = null; | |
| 151 | + if (declaredFrozenType != null && declaredFrozenType.subTypes != null && declaredFrozenType.subTypes.size() > i) | |
| 152 | + childDeclaredFrozenType = declaredFrozenType.subTypes.get(i); | |
| 153 | + checkFrozenTypes(childJavaType, childDeclaredFrozenType, false); | |
| 172 | 154 | } |
| 173 | 155 | } |
| 174 | 156 | } |
| 175 | 157 | |
| 176 | - private static void checkValidFrozen(Class<?> clazz, boolean declared) { | |
| 177 | - boolean expected = !EXPECTED_NON_FROZEN_CLASSES.contains(clazz) && !clazz.isEnum(); | |
| 178 | - if (expected != declared) | |
| 158 | + private static void checkValidFrozen(Class<?> clazz, boolean isRoot, boolean isDeclaredFrozen) { | |
| 159 | + boolean shouldBeFrozen = (TypeMappings.mapsToCollection(clazz) && !isRoot) | |
| 160 | + || TypeMappings.mapsToUserTypeOrTuple(clazz); | |
| 161 | + if (shouldBeFrozen != isDeclaredFrozen) | |
| 179 | 162 | throw new IllegalArgumentException(String.format("expected %s to be %sfrozen but was %sfrozen", |
| 180 | - clazz.getSimpleName(), | |
| 181 | - expected ? "" : "not ", | |
| 182 | - declared ? "" : "not ")); | |
| 163 | + clazz.getSimpleName(), | |
| 164 | + shouldBeFrozen ? "" : "not ", | |
| 165 | + isDeclaredFrozen ? "" : "not ")); | |
| 183 | 166 | } |
| 184 | 167 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +15 −35
| @@ -16,26 +16,21 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import java.lang.annotation.Annotation; |
| 19 | -import java.lang.reflect.*; | |
| 20 | 19 | import java.lang.reflect.Field; |
| 21 | -import java.util.*; | |
| 22 | - | |
| 23 | -import com.google.common.collect.ImmutableSet.Builder; | |
| 24 | -import com.google.common.collect.ImmutableSet; | |
| 20 | +import java.lang.reflect.*; | |
| 21 | +import java.util.ArrayList; | |
| 22 | +import java.util.Collections; | |
| 23 | +import java.util.Comparator; | |
| 24 | +import java.util.List; | |
| 25 | 25 | |
| 26 | -import com.datastax.driver.mapping.annotations.Frozen; | |
| 26 | +import com.google.common.base.Strings; | |
| 27 | 27 | |
| 28 | 28 | import com.datastax.driver.core.ConsistencyLevel; |
| 29 | -import com.datastax.driver.core.DataType; | |
| 30 | - | |
| 29 | +import com.datastax.driver.mapping.MethodMapper.EnumParamMapper; | |
| 30 | +import com.datastax.driver.mapping.MethodMapper.NestedUDTParamMapper; | |
| 31 | 31 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| 32 | -import com.datastax.driver.mapping.MethodMapper.UDTListParamMapper; | |
| 33 | -import com.datastax.driver.mapping.MethodMapper.UDTMapParamMapper; | |
| 34 | 32 | import com.datastax.driver.mapping.MethodMapper.UDTParamMapper; |
| 35 | -import com.datastax.driver.mapping.MethodMapper.UDTSetParamMapper; | |
| 36 | -import com.datastax.driver.mapping.MethodMapper.EnumParamMapper; | |
| 37 | 33 | import com.datastax.driver.mapping.annotations.*; |
| 38 | -import com.google.common.base.Strings; | |
| 39 | 34 | |
| 40 | 35 | /** |
| 41 | 36 | * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}. |
| @@ -291,29 +286,14 @@ | ||
| 291 | 286 | } |
| 292 | 287 | return new ParamMapper(paramName, idx); |
| 293 | 288 | } if (paramType instanceof ParameterizedType) { |
| 294 | - ParameterizedType pt = (ParameterizedType) paramType; | |
| 295 | - Type raw = pt.getRawType(); | |
| 296 | - if (!(raw instanceof Class)) | |
| 297 | - throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName)); | |
| 298 | - Class<?> klass = (Class<?>)raw; | |
| 299 | - Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, paramName); | |
| 300 | - if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) { | |
| 301 | - UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam); | |
| 302 | - return new UDTListParamMapper(paramName, idx, valueMapper); | |
| 303 | - } | |
| 304 | - if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) { | |
| 305 | - UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam); | |
| 306 | - return new UDTSetParamMapper(paramName, idx, valueMapper); | |
| 289 | + InferredCQLType inferredCQLType = InferredCQLType.from(className, methodName, idx, paramName, paramType, mappingManager); | |
| 290 | + if (inferredCQLType.containsMappedUDT) { | |
| 291 | + // We need a specialized mapper to convert UDT instances in the hierarchy. | |
| 292 | + return new NestedUDTParamMapper(paramName, idx, inferredCQLType); | |
| 293 | + } else { | |
| 294 | + // Use the default mapper but provide the extracted type | |
| 295 | + return new ParamMapper(paramName, idx, inferredCQLType.dataType); | |
| 307 | 296 | } |
| 308 | - if (Map.class.isAssignableFrom(klass)) { | |
| 309 | - Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, paramName); | |
| 310 | - UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null; | |
| 311 | - UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null; | |
| 312 | - if (keyMapper != null || valueMapper != null) { | |
| 313 | - return new UDTMapParamMapper(paramName, idx, keyMapper, valueMapper); | |
| 314 | - } | |
| 315 | - } | |
| 316 | - return new ParamMapper(paramName, idx); | |
| 317 | 297 | } else { |
| 318 | 298 | throw new IllegalArgumentException(String.format("Cannot map class %s for parameter %s of %s.%s", paramType, paramName, className, methodName)); |
| 319 | 299 | } |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/CQLType.java +0 −167
| @@ -1,167 +0,0 @@ | ||
| 1 | -package com.datastax.driver.mapping; | |
| 2 | - | |
| 3 | -import java.util.ArrayList; | |
| 4 | -import java.util.List; | |
| 5 | - | |
| 6 | -import com.datastax.driver.mapping.annotations.Frozen; | |
| 7 | -import com.google.common.base.Strings; | |
| 8 | - | |
| 9 | -/** A CQL type definition parsed from {@link Frozen#value()}, for example map<text,map<text,frozen<user>>> */ | |
| 10 | -class CQLType { | |
| 11 | - String name; | |
| 12 | - boolean frozen; | |
| 13 | - List<CQLType> subTypes; | |
| 14 | - | |
| 15 | - private CQLType(String name) { | |
| 16 | - this(name, false); | |
| 17 | - } | |
| 18 | - | |
| 19 | - private CQLType(String name, boolean frozen, CQLType... subTypes) { | |
| 20 | - this.name = name; | |
| 21 | - this.frozen = frozen; | |
| 22 | - for (CQLType subType : subTypes) { | |
| 23 | - if (this.subTypes == null) | |
| 24 | - this.subTypes = new ArrayList<CQLType>(); | |
| 25 | - this.subTypes.add(subType); | |
| 26 | - } | |
| 27 | - } | |
| 28 | - | |
| 29 | - // Some constant types for the simple cases. Note that we can afford generic names because currently we don't include the name in our | |
| 30 | - // checks. | |
| 31 | - static final CQLType FROZEN_SIMPLE = new CQLType("root", true); | |
| 32 | - static final CQLType FROZEN_ELEMENT = new CQLType("collection", false, | |
| 33 | - new CQLType("element", true)); | |
| 34 | - static final CQLType FROZEN_MAP_KEY = new CQLType("map", false, | |
| 35 | - new CQLType("key", true)); | |
| 36 | - static final CQLType FROZEN_MAP_VALUE = new CQLType("map", false, | |
| 37 | - new CQLType("key", false), | |
| 38 | - new CQLType("value", true)); | |
| 39 | - static final CQLType FROZEN_MAP_KEY_AND_VALUE = new CQLType("map", false, | |
| 40 | - new CQLType("key", true), | |
| 41 | - new CQLType("value", true)); | |
| 42 | - static final CQLType UNFROZEN_SIMPLE = new CQLType("root"); | |
| 43 | - | |
| 44 | - static CQLType parse(String toParse) { | |
| 45 | - if (Strings.isNullOrEmpty(toParse)) | |
| 46 | - // we allow that as a shorthand | |
| 47 | - return FROZEN_SIMPLE; | |
| 48 | - else | |
| 49 | - return new Parser(toParse).parse(); | |
| 50 | - } | |
| 51 | - | |
| 52 | - private static class Parser { | |
| 53 | - private final String toParse; | |
| 54 | - private int idx; | |
| 55 | - | |
| 56 | - Parser(String toParse) { | |
| 57 | - this.toParse = toParse; | |
| 58 | - } | |
| 59 | - | |
| 60 | - CQLType parse() { | |
| 61 | - skipSpaces(); | |
| 62 | - | |
| 63 | - if (toParse.charAt(idx) == '"') { | |
| 64 | - // quoted identifier: just return everything up to the next quote | |
| 65 | - int endQuote = idx + 1; | |
| 66 | - while (endQuote < toParse.length() && toParse.charAt(endQuote) != '"') | |
| 67 | - endQuote += 1; | |
| 68 | - if (endQuote == toParse.length()) | |
| 69 | - throw fail("could not find matching quote"); | |
| 70 | - if (endQuote == idx + 1) | |
| 71 | - throw fail("empty quoted identifier"); | |
| 72 | - | |
| 73 | - String name = toParse.substring(idx + 1, endQuote); | |
| 74 | - idx = endQuote + 1; | |
| 75 | - // a quoted identifier cannot be parameterized, so we can return immediately | |
| 76 | - return new CQLType(name); | |
| 77 | - } else { | |
| 78 | - // unquoted identifier: could be "simpleType", "complexType<subType1, subType2...>" or "frozen<type>" | |
| 79 | - int n = skipWord(); | |
| 80 | - String nextWord = toParse.substring(idx, n).toLowerCase(); | |
| 81 | - idx = n; | |
| 82 | - if ("frozen".equals(nextWord)) { | |
| 83 | - skipSpaces(); | |
| 84 | - if (idx >= toParse.length() || toParse.charAt(idx) != '<') | |
| 85 | - throw fail("expected '<'"); | |
| 86 | - idx += 1; | |
| 87 | - CQLType type = parse(); | |
| 88 | - skipSpaces(); | |
| 89 | - if (idx >= toParse.length() || toParse.charAt(idx) != '>') | |
| 90 | - throw fail("expected '>'"); | |
| 91 | - idx += 1; | |
| 92 | - type.frozen = true; | |
| 93 | - return type; | |
| 94 | - } else { | |
| 95 | - CQLType type = new CQLType(nextWord); | |
| 96 | - skipSpaces(); | |
| 97 | - if (idx < toParse.length() && toParse.charAt(idx) == '<') { | |
| 98 | - idx += 1; | |
| 99 | - type.subTypes = new ArrayList<CQLType>(); | |
| 100 | - while (idx < toParse.length()) { | |
| 101 | - type.subTypes.add(parse()); | |
| 102 | - skipSpaces(); | |
| 103 | - if (idx >= toParse.length()) | |
| 104 | - fail("unterminated list of subtypes"); | |
| 105 | - else if (toParse.charAt(idx) == '>') { | |
| 106 | - idx += 1; | |
| 107 | - break; | |
| 108 | - } | |
| 109 | - else if (toParse.charAt(idx) != ',') | |
| 110 | - fail("expected ','"); | |
| 111 | - else | |
| 112 | - idx += 1; | |
| 113 | - } | |
| 114 | - } | |
| 115 | - return type; | |
| 116 | - } | |
| 117 | - } | |
| 118 | - } | |
| 119 | - | |
| 120 | - private void skipSpaces() { | |
| 121 | - while (idx < toParse.length() && isBlank(idx)) | |
| 122 | - idx += 1; | |
| 123 | - } | |
| 124 | - | |
| 125 | - private int skipWord() { | |
| 126 | - if (idx >= toParse.length()) | |
| 127 | - throw fail("expected type name"); | |
| 128 | - | |
| 129 | - if (!isIdentStart(idx)) | |
| 130 | - throw fail("illegal character at start of type name"); | |
| 131 | - | |
| 132 | - int i = idx; | |
| 133 | - while (i < toParse.length() && isIdentBody(i)) | |
| 134 | - i += 1; | |
| 135 | - | |
| 136 | - return i; | |
| 137 | - } | |
| 138 | - | |
| 139 | - private boolean isBlank(int i) { | |
| 140 | - char c = toParse.charAt(i); | |
| 141 | - return c == ' ' || c == '\t' || c == '\n'; | |
| 142 | - } | |
| 143 | - | |
| 144 | - private boolean isIdentStart(int i) { | |
| 145 | - char c = toParse.charAt(i); | |
| 146 | - return isLetter(c); | |
| 147 | - } | |
| 148 | - | |
| 149 | - private boolean isIdentBody(int i) { | |
| 150 | - char c = toParse.charAt(i); | |
| 151 | - return isLetter(c) || isDigit(c) || c == '_'; | |
| 152 | - } | |
| 153 | - | |
| 154 | - private boolean isLetter(char c) { | |
| 155 | - return (c >= 'a' && c <= 'z') || | |
| 156 | - (c >= 'A' && c <= 'Z'); | |
| 157 | - } | |
| 158 | - | |
| 159 | - private boolean isDigit(char c) { | |
| 160 | - return (c >= '0' && c <= '9'); | |
| 161 | - } | |
| 162 | - | |
| 163 | - private IllegalArgumentException fail(String cause) { | |
| 164 | - return new IllegalArgumentException(cause + " (" + toParse + " [" + idx + "])"); | |
| 165 | - } | |
| 166 | - } | |
| 167 | -} |
added driver-mapping/src/main/java/com/datastax/driver/mapping/DeclaredFrozenType.java +170 −0
| @@ -0,0 +1,170 @@ | ||
| 1 | +package com.datastax.driver.mapping; | |
| 2 | + | |
| 3 | +import java.util.ArrayList; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +import com.datastax.driver.mapping.annotations.Frozen; | |
| 7 | +import com.google.common.base.Strings; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * A tree-like structure parsed from {@code Frozen*} annotations, that indicates which | |
| 11 | + * types in the hierarchy were declared frozen. | |
| 12 | + */ | |
| 13 | +class DeclaredFrozenType { | |
| 14 | + String name; | |
| 15 | + boolean frozen; | |
| 16 | + List<DeclaredFrozenType> subTypes; | |
| 17 | + | |
| 18 | + private DeclaredFrozenType(String name) { | |
| 19 | + this(name, false); | |
| 20 | + } | |
| 21 | + | |
| 22 | + private DeclaredFrozenType(String name, boolean frozen, DeclaredFrozenType... subTypes) { | |
| 23 | + this.name = name; | |
| 24 | + this.frozen = frozen; | |
| 25 | + for (DeclaredFrozenType subType : subTypes) { | |
| 26 | + if (this.subTypes == null) | |
| 27 | + this.subTypes = new ArrayList<DeclaredFrozenType>(); | |
| 28 | + this.subTypes.add(subType); | |
| 29 | + } | |
| 30 | + } | |
| 31 | + | |
| 32 | + // Some constant types for the simple cases. Note that we can afford generic names because currently we don't include the name in our | |
| 33 | + // checks. | |
| 34 | + static final DeclaredFrozenType FROZEN_SIMPLE = new DeclaredFrozenType("root", true); | |
| 35 | + static final DeclaredFrozenType FROZEN_ELEMENT = new DeclaredFrozenType("collection", false, | |
| 36 | + new DeclaredFrozenType("element", true)); | |
| 37 | + static final DeclaredFrozenType FROZEN_MAP_KEY = new DeclaredFrozenType("map", false, | |
| 38 | + new DeclaredFrozenType("key", true)); | |
| 39 | + static final DeclaredFrozenType FROZEN_MAP_VALUE = new DeclaredFrozenType("map", false, | |
| 40 | + new DeclaredFrozenType("key", false), | |
| 41 | + new DeclaredFrozenType("value", true)); | |
| 42 | + static final DeclaredFrozenType FROZEN_MAP_KEY_AND_VALUE = new DeclaredFrozenType("map", false, | |
| 43 | + new DeclaredFrozenType("key", true), | |
| 44 | + new DeclaredFrozenType("value", true)); | |
| 45 | + static final DeclaredFrozenType UNFROZEN_SIMPLE = new DeclaredFrozenType("root"); | |
| 46 | + | |
| 47 | + static DeclaredFrozenType parse(String toParse) { | |
| 48 | + if (Strings.isNullOrEmpty(toParse)) | |
| 49 | + // we allow that as a shorthand | |
| 50 | + return FROZEN_SIMPLE; | |
| 51 | + else | |
| 52 | + return new Parser(toParse).parse(); | |
| 53 | + } | |
| 54 | + | |
| 55 | + private static class Parser { | |
| 56 | + private final String toParse; | |
| 57 | + private int idx; | |
| 58 | + | |
| 59 | + Parser(String toParse) { | |
| 60 | + this.toParse = toParse; | |
| 61 | + } | |
| 62 | + | |
| 63 | + DeclaredFrozenType parse() { | |
| 64 | + skipSpaces(); | |
| 65 | + | |
| 66 | + if (toParse.charAt(idx) == '"') { | |
| 67 | + // quoted identifier: just return everything up to the next quote | |
| 68 | + int endQuote = idx + 1; | |
| 69 | + while (endQuote < toParse.length() && toParse.charAt(endQuote) != '"') | |
| 70 | + endQuote += 1; | |
| 71 | + if (endQuote == toParse.length()) | |
| 72 | + throw fail("could not find matching quote"); | |
| 73 | + if (endQuote == idx + 1) | |
| 74 | + throw fail("empty quoted identifier"); | |
| 75 | + | |
| 76 | + String name = toParse.substring(idx + 1, endQuote); | |
| 77 | + idx = endQuote + 1; | |
| 78 | + // a quoted identifier cannot be parameterized, so we can return immediately | |
| 79 | + return new DeclaredFrozenType(name); | |
| 80 | + } else { | |
| 81 | + // unquoted identifier: could be "simpleType", "complexType<subType1, subType2...>" or "frozen<type>" | |
| 82 | + int n = skipWord(); | |
| 83 | + String nextWord = toParse.substring(idx, n).toLowerCase(); | |
| 84 | + idx = n; | |
| 85 | + if ("frozen".equals(nextWord)) { | |
| 86 | + skipSpaces(); | |
| 87 | + if (idx >= toParse.length() || toParse.charAt(idx) != '<') | |
| 88 | + throw fail("expected '<'"); | |
| 89 | + idx += 1; | |
| 90 | + DeclaredFrozenType type = parse(); | |
| 91 | + skipSpaces(); | |
| 92 | + if (idx >= toParse.length() || toParse.charAt(idx) != '>') | |
| 93 | + throw fail("expected '>'"); | |
| 94 | + idx += 1; | |
| 95 | + type.frozen = true; | |
| 96 | + return type; | |
| 97 | + } else { | |
| 98 | + DeclaredFrozenType type = new DeclaredFrozenType(nextWord); | |
| 99 | + skipSpaces(); | |
| 100 | + if (idx < toParse.length() && toParse.charAt(idx) == '<') { | |
| 101 | + idx += 1; | |
| 102 | + type.subTypes = new ArrayList<DeclaredFrozenType>(); | |
| 103 | + while (idx < toParse.length()) { | |
| 104 | + type.subTypes.add(parse()); | |
| 105 | + skipSpaces(); | |
| 106 | + if (idx >= toParse.length()) | |
| 107 | + fail("unterminated list of subtypes"); | |
| 108 | + else if (toParse.charAt(idx) == '>') { | |
| 109 | + idx += 1; | |
| 110 | + break; | |
| 111 | + } | |
| 112 | + else if (toParse.charAt(idx) != ',') | |
| 113 | + fail("expected ','"); | |
| 114 | + else | |
| 115 | + idx += 1; | |
| 116 | + } | |
| 117 | + } | |
| 118 | + return type; | |
| 119 | + } | |
| 120 | + } | |
| 121 | + } | |
| 122 | + | |
| 123 | + private void skipSpaces() { | |
| 124 | + while (idx < toParse.length() && isBlank(idx)) | |
| 125 | + idx += 1; | |
| 126 | + } | |
| 127 | + | |
| 128 | + private int skipWord() { | |
| 129 | + if (idx >= toParse.length()) | |
| 130 | + throw fail("expected type name"); | |
| 131 | + | |
| 132 | + if (!isIdentStart(idx)) | |
| 133 | + throw fail("illegal character at start of type name"); | |
| 134 | + | |
| 135 | + int i = idx; | |
| 136 | + while (i < toParse.length() && isIdentBody(i)) | |
| 137 | + i += 1; | |
| 138 | + | |
| 139 | + return i; | |
| 140 | + } | |
| 141 | + | |
| 142 | + private boolean isBlank(int i) { | |
| 143 | + char c = toParse.charAt(i); | |
| 144 | + return c == ' ' || c == '\t' || c == '\n'; | |
| 145 | + } | |
| 146 | + | |
| 147 | + private boolean isIdentStart(int i) { | |
| 148 | + char c = toParse.charAt(i); | |
| 149 | + return isLetter(c); | |
| 150 | + } | |
| 151 | + | |
| 152 | + private boolean isIdentBody(int i) { | |
| 153 | + char c = toParse.charAt(i); | |
| 154 | + return isLetter(c) || isDigit(c) || c == '_'; | |
| 155 | + } | |
| 156 | + | |
| 157 | + private boolean isLetter(char c) { | |
| 158 | + return (c >= 'a' && c <= 'z') || | |
| 159 | + (c >= 'A' && c <= 'Z'); | |
| 160 | + } | |
| 161 | + | |
| 162 | + private boolean isDigit(char c) { | |
| 163 | + return (c >= '0' && c <= '9'); | |
| 164 | + } | |
| 165 | + | |
| 166 | + private IllegalArgumentException fail(String cause) { | |
| 167 | + return new IllegalArgumentException(cause + " (" + toParse + " [" + idx + "])"); | |
| 168 | + } | |
| 169 | + } | |
| 170 | +} |
added driver-mapping/src/main/java/com/datastax/driver/mapping/InferredCQLType.java +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.mapping; | |
| 17 | + | |
| 18 | +import java.lang.reflect.Field; | |
| 19 | +import java.lang.reflect.ParameterizedType; | |
| 20 | +import java.lang.reflect.Type; | |
| 21 | +import java.util.Collections; | |
| 22 | +import java.util.List; | |
| 23 | + | |
| 24 | +import com.google.common.collect.Lists; | |
| 25 | + | |
| 26 | +import com.datastax.driver.core.DataType; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * Describes the CQL type inferred from a generic Java field (which will always map | |
| 30 | + * to a collection, possibly with various levels of nesting). | |
| 31 | + * | |
| 32 | + * The reason we wrap {@code DataType} is because we also want to remember if there are mapped UDT | |
| 33 | + * types somewhere in the hierarchy. | |
| 34 | + */ | |
| 35 | +class InferredCQLType { | |
| 36 | + final DataType dataType; | |
| 37 | + final boolean containsMappedUDT; | |
| 38 | + final UDTMapper udtMapper; | |
| 39 | + final List<InferredCQLType> childTypes; | |
| 40 | + | |
| 41 | + static InferredCQLType from(Field field, MappingManager mappingManager) { | |
| 42 | + String name = String.format("field %s of class %s", field.getName(), field.getDeclaringClass().getName()); | |
| 43 | + return new InferredCQLType(field.getGenericType(), name, field.getGenericType(), mappingManager); | |
| 44 | + } | |
| 45 | + | |
| 46 | + static InferredCQLType from(String className, String methodName, int idx, String paramName, Type paramType, MappingManager mappingManager) { | |
| 47 | + String name = String.format("parameter %s of %s.%s", paramName == null ? idx : paramName, className, methodName); | |
| 48 | + return new InferredCQLType(paramType, name, paramType, mappingManager); | |
| 49 | + } | |
| 50 | + | |
| 51 | + private InferredCQLType(Type javaType, String rootName, Type rootType, MappingManager mappingManager) { | |
| 52 | + if (javaType instanceof ParameterizedType) { | |
| 53 | + ParameterizedType pt = (ParameterizedType)javaType; | |
| 54 | + Type raw = pt.getRawType(); | |
| 55 | + if (!(raw instanceof Class)) | |
| 56 | + throw fail(rootName, rootType); | |
| 57 | + | |
| 58 | + Class<?> klass = (Class<?>)raw; | |
| 59 | + if (!TypeMappings.mapsToCollection(klass)) | |
| 60 | + throw fail(rootName, rootType); | |
| 61 | + | |
| 62 | + childTypes = Lists.newArrayList(); | |
| 63 | + boolean childrenContainMappedUDT = false; | |
| 64 | + for (Type childJavaType : pt.getActualTypeArguments()) { | |
| 65 | + InferredCQLType child = new InferredCQLType(childJavaType, rootName, rootType, mappingManager); | |
| 66 | + childrenContainMappedUDT |= child.containsMappedUDT; | |
| 67 | + childTypes.add(child); | |
| 68 | + } | |
| 69 | + containsMappedUDT = childrenContainMappedUDT; | |
| 70 | + udtMapper = null; | |
| 71 | + | |
| 72 | + if (TypeMappings.mapsToList(klass)) { | |
| 73 | + dataType = DataType.list(childTypes.get(0).dataType); | |
| 74 | + } else if (TypeMappings.mapsToSet(klass)) { | |
| 75 | + dataType = DataType.set(childTypes.get(0).dataType); | |
| 76 | + } else if (TypeMappings.mapsToMap(klass)) { | |
| 77 | + dataType = DataType.map(childTypes.get(0).dataType, childTypes.get(1).dataType); | |
| 78 | + } else | |
| 79 | + throw fail(rootName, rootType); | |
| 80 | + } else if (javaType instanceof Class) { | |
| 81 | + Class<?> klass = (Class<?>)javaType; | |
| 82 | + if (TypeMappings.isMappedUDT(klass)) { | |
| 83 | + containsMappedUDT = true; | |
| 84 | + udtMapper = mappingManager.udtMapper(klass); | |
| 85 | + dataType = udtMapper.getUserType(); | |
| 86 | + childTypes = Collections.emptyList(); | |
| 87 | + } else { | |
| 88 | + containsMappedUDT = false; | |
| 89 | + udtMapper = null; | |
| 90 | + dataType = TypeMappings.getSimpleType(klass, rootName); | |
| 91 | + childTypes = Collections.emptyList(); | |
| 92 | + } | |
| 93 | + } else { | |
| 94 | + throw fail(rootName, rootType); | |
| 95 | + } | |
| 96 | + } | |
| 97 | + | |
| 98 | + private IllegalArgumentException fail(String rootName, Type rootType) { | |
| 99 | + return new IllegalArgumentException(String.format("Cannot map class %s for %s", rootType, rootName)); | |
| 100 | + } | |
| 101 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +23 −47
| @@ -18,9 +18,7 @@ | ||
| 18 | 18 | import java.lang.reflect.Method; |
| 19 | 19 | import java.lang.reflect.ParameterizedType; |
| 20 | 20 | import java.lang.reflect.Type; |
| 21 | -import java.util.List; | |
| 22 | -import java.util.Map; | |
| 23 | -import java.util.Set; | |
| 21 | +import java.nio.ByteBuffer; | |
| 24 | 22 | |
| 25 | 23 | import com.google.common.util.concurrent.Futures; |
| 26 | 24 | import com.google.common.util.concurrent.ListenableFuture; |
| @@ -160,23 +158,32 @@ | ||
| 160 | 158 | // We'll only set one of the other. If paramName is null, then paramIdx is used. |
| 161 | 159 | private final String paramName; |
| 162 | 160 | private final int paramIdx; |
| 161 | + private final DataType dataType; | |
| 163 | 162 | |
| 164 | - public ParamMapper(String paramName, int paramIdx) { | |
| 163 | + public ParamMapper(String paramName, int paramIdx, DataType dataType) { | |
| 165 | 164 | this.paramName = paramName; |
| 166 | 165 | this.paramIdx = paramIdx; |
| 166 | + this.dataType = dataType; | |
| 167 | + } | |
| 168 | + | |
| 169 | + public ParamMapper(String paramName, int paramIdx) { | |
| 170 | + this(paramName, paramIdx, null); | |
| 167 | 171 | } |
| 168 | 172 | |
| 169 | 173 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 174 | + ByteBuffer serializedArg = (dataType == null) | |
| 175 | + ? DataType.serializeValue(arg, protocolVersion) | |
| 176 | + : dataType.serialize(arg, protocolVersion); | |
| 170 | 177 | if (paramName == null) { |
| 171 | 178 | if (arg == null) |
| 172 | 179 | boundStatement.setToNull(paramIdx); |
| 173 | 180 | else |
| 174 | - boundStatement.setBytesUnsafe(paramIdx, DataType.serializeValue(arg, protocolVersion)); | |
| 181 | + boundStatement.setBytesUnsafe(paramIdx, serializedArg); | |
| 175 | 182 | } else { |
| 176 | 183 | if (arg == null) |
| 177 | 184 | boundStatement.setToNull(paramName); |
| 178 | 185 | else |
| 179 | - boundStatement.setBytesUnsafe(paramName, DataType.serializeValue(arg, protocolVersion)); | |
| 186 | + boundStatement.setBytesUnsafe(paramName, serializedArg); | |
| 180 | 187 | } |
| 181 | 188 | } |
| 182 | 189 | } |
| @@ -198,53 +205,22 @@ | ||
| 198 | 205 | } |
| 199 | 206 | } |
| 200 | 207 | |
| 201 | - static class UDTListParamMapper<V> extends ParamMapper { | |
| 202 | - private final UDTMapper<V> valueMapper; | |
| 203 | - | |
| 204 | - UDTListParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) { | |
| 205 | - super(paramName, paramIdx); | |
| 206 | - this.valueMapper = valueMapper; | |
| 207 | - } | |
| 208 | - | |
| 209 | - @Override | |
| 210 | - void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { | |
| 211 | - @SuppressWarnings("unchecked") | |
| 212 | - List<V> entities = (List<V>) arg; | |
| 213 | - super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion); | |
| 214 | - } | |
| 215 | - } | |
| 216 | - | |
| 217 | - static class UDTSetParamMapper<V> extends ParamMapper { | |
| 218 | - private final UDTMapper<V> valueMapper; | |
| 219 | - | |
| 220 | - UDTSetParamMapper(String paramName, int paramIdx, UDTMapper<V> valueMapper) { | |
| 221 | - super(paramName, paramIdx); | |
| 222 | - this.valueMapper = valueMapper; | |
| 223 | - } | |
| 224 | - | |
| 225 | - @Override | |
| 226 | - void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { | |
| 227 | - @SuppressWarnings("unchecked") | |
| 228 | - Set<V> entities = (Set<V>) arg; | |
| 229 | - super.setValue(boundStatement, valueMapper.toUDTValues(entities), protocolVersion); | |
| 230 | - } | |
| 231 | - } | |
| 232 | - | |
| 233 | - static class UDTMapParamMapper<K, V> extends ParamMapper { | |
| 234 | - private final UDTMapper<K> keyMapper; | |
| 235 | - private final UDTMapper<V> valueMapper; | |
| 208 | + /** | |
| 209 | + * Maps a nested collection which has a mapped UDT somewhere in the hierarchy. | |
| 210 | + */ | |
| 211 | + static class NestedUDTParamMapper extends ParamMapper { | |
| 212 | + private final InferredCQLType inferredCQLType; | |
| 236 | 213 | |
| 237 | - UDTMapParamMapper(String paramName, int paramIdx, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) { | |
| 214 | + NestedUDTParamMapper(String paramName, int paramIdx, InferredCQLType inferredCQLType) { | |
| 238 | 215 | super(paramName, paramIdx); |
| 239 | - this.keyMapper = keyMapper; | |
| 240 | - this.valueMapper = valueMapper; | |
| 216 | + this.inferredCQLType = inferredCQLType; | |
| 241 | 217 | } |
| 242 | 218 | |
| 243 | 219 | @Override |
| 244 | 220 | void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) { |
| 245 | - @SuppressWarnings("unchecked") | |
| 246 | - Map<K, V> entities = (Map<K, V>) arg; | |
| 247 | - super.setValue(boundStatement, UDTMapper.toUDTValues(entities, keyMapper, valueMapper), protocolVersion); | |
| 221 | + super.setValue(boundStatement, | |
| 222 | + UDTMapper.convertEntitiesToUDTs(arg, inferredCQLType), | |
| 223 | + protocolVersion); | |
| 248 | 224 | } |
| 249 | 225 | } |
| 250 | 226 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +22 −167
| @@ -21,16 +21,10 @@ | ||
| 21 | 21 | import java.lang.reflect.ParameterizedType; |
| 22 | 22 | import java.lang.reflect.Type; |
| 23 | 23 | import java.lang.reflect.Method; |
| 24 | -import java.net.InetAddress; | |
| 25 | -import java.nio.ByteBuffer; | |
| 26 | -import java.math.BigInteger; | |
| 27 | -import java.math.BigDecimal; | |
| 28 | 24 | import java.util.*; |
| 29 | 25 | |
| 30 | 26 | import com.datastax.driver.core.*; |
| 31 | 27 | |
| 32 | -import com.datastax.driver.mapping.annotations.UDT; | |
| 33 | - | |
| 34 | 28 | /** |
| 35 | 29 | * An {@link EntityMapper} implementation that use reflection to read and write fields |
| 36 | 30 | * of an entity. |
| @@ -62,7 +56,7 @@ | ||
| 62 | 56 | private final Method writeMethod; |
| 63 | 57 | |
| 64 | 58 | private LiteralMapper(Field field, int position, PropertyDescriptor pd) { |
| 65 | - this(field, extractType(field), position, pd); | |
| 59 | + this(field, extractSimpleType(field), position, pd); | |
| 66 | 60 | } |
| 67 | 61 | |
| 68 | 62 | private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd) { |
| @@ -166,159 +160,36 @@ | ||
| 166 | 160 | } |
| 167 | 161 | } |
| 168 | 162 | |
| 169 | - private static class UDTListMapper<T, V> extends LiteralMapper<T> { | |
| 170 | - | |
| 171 | - private final UDTMapper<V> valueMapper; | |
| 172 | - | |
| 173 | - UDTListMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) { | |
| 174 | - super(field, DataType.list(valueMapper.getUserType()), position, pd); | |
| 175 | - this.valueMapper = valueMapper; | |
| 176 | - } | |
| 177 | - | |
| 178 | - @Override | |
| 179 | - public Object getValue(T entity) { | |
| 180 | - @SuppressWarnings("unchecked") | |
| 181 | - List<V> entities = (List<V>) super.getValue(entity); | |
| 182 | - return valueMapper.toUDTValues(entities); | |
| 183 | - } | |
| 184 | - | |
| 185 | - @Override | |
| 186 | - public void setValue(Object entity, Object value) { | |
| 187 | - @SuppressWarnings("unchecked") | |
| 188 | - List<UDTValue> udtValues = (List<UDTValue>) value; | |
| 189 | - super.setValue(entity, valueMapper.toEntities(udtValues)); | |
| 190 | - } | |
| 191 | - } | |
| 192 | - | |
| 193 | - private static class UDTSetMapper<T, V> extends LiteralMapper<T> { | |
| 194 | - | |
| 195 | - private final UDTMapper<V> valueMapper; | |
| 196 | - | |
| 197 | - UDTSetMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<V> valueMapper) { | |
| 198 | - super(field, DataType.set(valueMapper.getUserType()), position, pd); | |
| 199 | - this.valueMapper = valueMapper; | |
| 200 | - } | |
| 201 | - | |
| 202 | - @Override | |
| 203 | - public Object getValue(T entity) { | |
| 204 | - @SuppressWarnings("unchecked") | |
| 205 | - Set<V> entities = (Set<V>) super.getValue(entity); | |
| 206 | - return valueMapper.toUDTValues(entities); | |
| 207 | - } | |
| 208 | - | |
| 209 | - @Override | |
| 210 | - public void setValue(Object entity, Object value) { | |
| 211 | - @SuppressWarnings("unchecked") | |
| 212 | - Set<UDTValue> udtValues = (Set<UDTValue>) value; | |
| 213 | - super.setValue(entity, valueMapper.toEntities(udtValues)); | |
| 214 | - } | |
| 215 | - } | |
| 163 | + private static class NestedUDTMapper<T> extends LiteralMapper<T> { | |
| 164 | + private final InferredCQLType inferredCQLType; | |
| 216 | 165 | |
| 217 | - /** | |
| 218 | - * A map field that contains UDT values. | |
| 219 | - * <p> | |
| 220 | - * UDTs may be used either as keys, or as values, or both. This is reflected | |
| 221 | - * in keyMapper and valueMapper being null or non-null. | |
| 222 | - * </p> | |
| 223 | - */ | |
| 224 | - private static class UDTMapMapper<T, K, V> extends LiteralMapper<T> { | |
| 225 | - private final UDTMapper<K> keyMapper; | |
| 226 | - private final UDTMapper<V> valueMapper; | |
| 227 | - | |
| 228 | - UDTMapMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) { | |
| 229 | - super(field, buildDataType(field, keyMapper, valueMapper, keyClass, valueClass), position, pd); | |
| 230 | - this.keyMapper = keyMapper; | |
| 231 | - this.valueMapper = valueMapper; | |
| 166 | + public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType) { | |
| 167 | + super(field, inferredCQLType.dataType, position, pd); | |
| 168 | + this.inferredCQLType = inferredCQLType; | |
| 232 | 169 | } |
| 233 | 170 | |
| 234 | 171 | @Override |
| 172 | + @SuppressWarnings("unchecked") | |
| 235 | 173 | public Object getValue(T entity) { |
| 236 | - @SuppressWarnings("unchecked") | |
| 237 | - Map<K, V> entities = (Map<K, V>) super.getValue(entity); | |
| 238 | - return UDTMapper.toUDTValues(entities, keyMapper, valueMapper); | |
| 174 | + Object valueWithEntities = super.getValue(entity); | |
| 175 | + return (T)UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType); | |
| 239 | 176 | } |
| 240 | 177 | |
| 241 | 178 | @Override |
| 242 | - @SuppressWarnings("unchecked") | |
| 243 | - public void setValue(Object entity, Object fieldValue) { | |
| 244 | - Map<Object, Object> udtValues = (Map<Object, Object>) fieldValue; | |
| 245 | - super.setValue(entity, UDTMapper.toEntities(udtValues, keyMapper, valueMapper)); | |
| 246 | - } | |
| 247 | - | |
| 248 | - private static <K, V> DataType buildDataType(Field field, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper, Class<?> keyClass, Class<?> valueClass) { | |
| 249 | - assert keyMapper != null || valueMapper != null; | |
| 250 | - | |
| 251 | - DataType keyType = (keyMapper != null) ? | |
| 252 | - keyMapper.getUserType() : | |
| 253 | - getSimpleType(keyClass, field); | |
| 254 | - DataType valueType = (valueMapper != null) ? | |
| 255 | - valueMapper.getUserType() : | |
| 256 | - getSimpleType(valueClass, field); | |
| 257 | - return DataType.map(keyType, valueType); | |
| 179 | + public void setValue(Object entity, Object valueWithUDTValues) { | |
| 180 | + super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType)); | |
| 258 | 181 | } |
| 259 | 182 | } |
| 260 | 183 | |
| 261 | - static DataType extractType(Field f) { | |
| 184 | + static DataType extractSimpleType(Field f) { | |
| 262 | 185 | Type type = f.getGenericType(); |
| 263 | 186 | |
| 264 | - if (type instanceof ParameterizedType) { | |
| 265 | - ParameterizedType pt = (ParameterizedType)type; | |
| 266 | - Type raw = pt.getRawType(); | |
| 267 | - if (!(raw instanceof Class)) | |
| 268 | - throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName())); | |
| 269 | - | |
| 270 | - Class<?> klass = (Class<?>)raw; | |
| 271 | - if (List.class.isAssignableFrom(klass)) { | |
| 272 | - return DataType.list(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f)); | |
| 273 | - } | |
| 274 | - if (Set.class.isAssignableFrom(klass)) { | |
| 275 | - return DataType.set(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f)); | |
| 276 | - } | |
| 277 | - if (Map.class.isAssignableFrom(klass)) { | |
| 278 | - return DataType.map(getSimpleType(ReflectionUtils.getParam(pt, 0, f.getName()), f), getSimpleType(ReflectionUtils.getParam(pt, 1, f.getName()), f)); | |
| 279 | - } | |
| 280 | - throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName())); | |
| 281 | - } | |
| 187 | + assert !(type instanceof ParameterizedType); | |
| 282 | 188 | |
| 283 | 189 | if (!(type instanceof Class)) |
| 284 | 190 | throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", type, f.getName())); |
| 285 | 191 | |
| 286 | - return getSimpleType((Class<?>)type, f); | |
| 287 | - } | |
| 288 | - | |
| 289 | - static DataType getSimpleType(Class<?> klass, Field f) { | |
| 290 | - if (ByteBuffer.class.isAssignableFrom(klass)) | |
| 291 | - return DataType.blob(); | |
| 292 | - | |
| 293 | - if (klass == int.class || Integer.class.isAssignableFrom(klass)) | |
| 294 | - return DataType.cint(); | |
| 295 | - if (klass == long.class || Long.class.isAssignableFrom(klass)) | |
| 296 | - return DataType.bigint(); | |
| 297 | - if (klass == float.class || Float.class.isAssignableFrom(klass)) | |
| 298 | - return DataType.cfloat(); | |
| 299 | - if (klass == double.class || Double.class.isAssignableFrom(klass)) | |
| 300 | - return DataType.cdouble(); | |
| 301 | - if (klass == boolean.class || Boolean.class.isAssignableFrom(klass)) | |
| 302 | - return DataType.cboolean(); | |
| 303 | - | |
| 304 | - if (BigDecimal.class.isAssignableFrom(klass)) | |
| 305 | - return DataType.decimal(); | |
| 306 | - if (BigInteger.class.isAssignableFrom(klass)) | |
| 307 | - return DataType.varint(); | |
| 308 | - | |
| 309 | - if (String.class.isAssignableFrom(klass)) | |
| 310 | - return DataType.text(); | |
| 311 | - if (InetAddress.class.isAssignableFrom(klass)) | |
| 312 | - return DataType.inet(); | |
| 313 | - if (Date.class.isAssignableFrom(klass)) | |
| 314 | - return DataType.timestamp(); | |
| 315 | - if (UUID.class.isAssignableFrom(klass)) | |
| 316 | - return DataType.uuid(); | |
| 317 | - | |
| 318 | - if (Collection.class.isAssignableFrom(klass)) | |
| 319 | - throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), f.getName())); | |
| 320 | - | |
| 321 | - throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), f)); | |
| 192 | + return TypeMappings.getSimpleType((Class<?>)type, f.getName()); | |
| 322 | 193 | } |
| 323 | 194 | |
| 324 | 195 | private static class ReflectionFactory implements Factory { |
| @@ -337,35 +208,19 @@ | ||
| 337 | 208 | return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field)); |
| 338 | 209 | } |
| 339 | 210 | |
| 340 | - if (field.getType().isAnnotationPresent(UDT.class)) { | |
| 211 | + if (TypeMappings.isMappedUDT(field.getType())) { | |
| 341 | 212 | UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType()); |
| 342 | 213 | return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper); |
| 343 | 214 | } |
| 344 | 215 | |
| 345 | 216 | if (field.getGenericType() instanceof ParameterizedType) { |
| 346 | - ParameterizedType pt = (ParameterizedType) field.getGenericType(); | |
| 347 | - Type raw = pt.getRawType(); | |
| 348 | - if (!(raw instanceof Class)) | |
| 349 | - throw new IllegalArgumentException(String.format("Cannot map class %s for field %s", field, field.getName())); | |
| 350 | - | |
| 351 | - Class<?> klass = (Class<?>)raw; | |
| 352 | - Class<?> firstTypeParam = ReflectionUtils.getParam(pt, 0, field.getName()); | |
| 353 | - if (List.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) { | |
| 354 | - UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam); | |
| 355 | - return (ColumnMapper<T>) new UDTListMapper(field, position, pd, valueMapper); | |
| 356 | - } | |
| 357 | - if (Set.class.isAssignableFrom(klass) && firstTypeParam.isAnnotationPresent(UDT.class)) { | |
| 358 | - UDTMapper<?> valueMapper = mappingManager.getUDTMapper(firstTypeParam); | |
| 359 | - return (ColumnMapper<T>) new UDTSetMapper(field, position, pd, valueMapper); | |
| 360 | - } | |
| 361 | - if (Map.class.isAssignableFrom(klass)) { | |
| 362 | - Class<?> secondTypeParam = ReflectionUtils.getParam(pt, 1, field.getName()); | |
| 363 | - UDTMapper<?> keyMapper = firstTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(firstTypeParam) : null; | |
| 364 | - UDTMapper<?> valueMapper = secondTypeParam.isAnnotationPresent(UDT.class) ? mappingManager.getUDTMapper(secondTypeParam) : null; | |
| 365 | - | |
| 366 | - if (keyMapper != null || valueMapper != null) { | |
| 367 | - return (ColumnMapper<T>) new UDTMapMapper(field, position, pd, keyMapper, valueMapper, firstTypeParam, secondTypeParam); | |
| 368 | - } | |
| 217 | + InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager); | |
| 218 | + if (inferredCQLType.containsMappedUDT) { | |
| 219 | + // We need a specialized mapper to convert UDT instances in the hierarchy. | |
| 220 | + return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType); | |
| 221 | + } else { | |
| 222 | + // The default codecs will know how to handle the extracted datatype. | |
| 223 | + return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd); | |
| 369 | 224 | } |
| 370 | 225 | } |
| 371 | 226 |
added driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +95 −0
| @@ -0,0 +1,95 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.mapping; | |
| 17 | + | |
| 18 | +import java.lang.reflect.Field; | |
| 19 | +import java.math.BigDecimal; | |
| 20 | +import java.math.BigInteger; | |
| 21 | +import java.net.InetAddress; | |
| 22 | +import java.nio.ByteBuffer; | |
| 23 | +import java.util.*; | |
| 24 | + | |
| 25 | +import com.datastax.driver.core.DataType; | |
| 26 | +import com.datastax.driver.core.TupleValue; | |
| 27 | +import com.datastax.driver.core.UDTValue; | |
| 28 | +import com.datastax.driver.mapping.annotations.UDT; | |
| 29 | + | |
| 30 | +/** | |
| 31 | + * Utility methods to determine which CQL type we expect for a given Java field type. | |
| 32 | + */ | |
| 33 | +class TypeMappings { | |
| 34 | + | |
| 35 | + static DataType getSimpleType(Class<?> klass, String fieldName) { | |
| 36 | + if (ByteBuffer.class.isAssignableFrom(klass)) | |
| 37 | + return DataType.blob(); | |
| 38 | + | |
| 39 | + if (klass == int.class || Integer.class.isAssignableFrom(klass)) | |
| 40 | + return DataType.cint(); | |
| 41 | + if (klass == long.class || Long.class.isAssignableFrom(klass)) | |
| 42 | + return DataType.bigint(); | |
| 43 | + if (klass == float.class || Float.class.isAssignableFrom(klass)) | |
| 44 | + return DataType.cfloat(); | |
| 45 | + if (klass == double.class || Double.class.isAssignableFrom(klass)) | |
| 46 | + return DataType.cdouble(); | |
| 47 | + if (klass == boolean.class || Boolean.class.isAssignableFrom(klass)) | |
| 48 | + return DataType.cboolean(); | |
| 49 | + | |
| 50 | + if (BigDecimal.class.isAssignableFrom(klass)) | |
| 51 | + return DataType.decimal(); | |
| 52 | + if (BigInteger.class.isAssignableFrom(klass)) | |
| 53 | + return DataType.varint(); | |
| 54 | + | |
| 55 | + if (String.class.isAssignableFrom(klass)) | |
| 56 | + return DataType.text(); | |
| 57 | + if (InetAddress.class.isAssignableFrom(klass)) | |
| 58 | + return DataType.inet(); | |
| 59 | + if (Date.class.isAssignableFrom(klass)) | |
| 60 | + return DataType.timestamp(); | |
| 61 | + if (UUID.class.isAssignableFrom(klass)) | |
| 62 | + return DataType.uuid(); | |
| 63 | + | |
| 64 | + if (Collection.class.isAssignableFrom(klass)) | |
| 65 | + throw new IllegalArgumentException(String.format("Cannot map non-parametrized collection type %s for field %s; Please use a concrete type parameter", klass.getName(), fieldName)); | |
| 66 | + | |
| 67 | + throw new IllegalArgumentException(String.format("Cannot map unknown class %s for field %s", klass.getName(), fieldName)); | |
| 68 | + } | |
| 69 | + | |
| 70 | + static boolean mapsToList(Class<?> klass) { | |
| 71 | + return List.class.equals(klass); | |
| 72 | + } | |
| 73 | + | |
| 74 | + static boolean mapsToSet(Class<?> klass) { | |
| 75 | + return Set.class.equals(klass); | |
| 76 | + } | |
| 77 | + | |
| 78 | + static boolean mapsToMap(Class<?> klass) { | |
| 79 | + return Map.class.equals(klass); | |
| 80 | + } | |
| 81 | + | |
| 82 | + static boolean mapsToCollection(Class<?> klass) { | |
| 83 | + return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass); | |
| 84 | + } | |
| 85 | + | |
| 86 | + static boolean isMappedUDT(Class<?> klass) { | |
| 87 | + return klass.isAnnotationPresent(UDT.class); | |
| 88 | + } | |
| 89 | + | |
| 90 | + static boolean mapsToUserTypeOrTuple(Class<?> klass) { | |
| 91 | + return isMappedUDT(klass) || | |
| 92 | + klass.equals(UDTValue.class) || | |
| 93 | + klass.equals(TupleValue.class); | |
| 94 | + } | |
| 95 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/UDTMapper.java +81 −66
| @@ -19,9 +19,6 @@ | ||
| 19 | 19 | import java.util.*; |
| 20 | 20 | import java.util.Map.Entry; |
| 21 | 21 | |
| 22 | -import com.google.common.collect.Maps; | |
| 23 | -import com.google.common.collect.Sets; | |
| 24 | - | |
| 25 | 22 | import com.datastax.driver.core.*; |
| 26 | 23 | |
| 27 | 24 | /** |
| @@ -88,51 +85,6 @@ | ||
| 88 | 85 | return userType; |
| 89 | 86 | } |
| 90 | 87 | |
| 91 | - List<UDTValue> toUDTValues(List<T> entities) { | |
| 92 | - if (entities == null) | |
| 93 | - return null; | |
| 94 | - | |
| 95 | - List<UDTValue> udtValues = new ArrayList<UDTValue>(entities.size()); | |
| 96 | - for (T entity : entities) { | |
| 97 | - UDTValue udtValue = toUDT(entity); | |
| 98 | - udtValues.add(udtValue); | |
| 99 | - } | |
| 100 | - return udtValues; | |
| 101 | - } | |
| 102 | - | |
| 103 | - Set<UDTValue> toUDTValues(Set<T> entities) { | |
| 104 | - if (entities == null) | |
| 105 | - return null; | |
| 106 | - | |
| 107 | - Set<UDTValue> udtValues = Sets.newHashSetWithExpectedSize(entities.size()); | |
| 108 | - for (T entity : entities) { | |
| 109 | - UDTValue udtValue = toUDT(entity); | |
| 110 | - udtValues.add(udtValue); | |
| 111 | - } | |
| 112 | - return udtValues; | |
| 113 | - } | |
| 114 | - | |
| 115 | - /* | |
| 116 | - * Map conversion methods are static because they use two mappers, either of | |
| 117 | - * which (but not both) may be null. | |
| 118 | - * | |
| 119 | - * This reflects the fact that the map datatype can use UDTs as keys, or | |
| 120 | - * values, or both. | |
| 121 | - */ | |
| 122 | - static <K, V> Map<Object, Object> toUDTValues(Map<K, V> entities, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) { | |
| 123 | - assert keyMapper != null || valueMapper != null; | |
| 124 | - if (entities == null) | |
| 125 | - return null; | |
| 126 | - | |
| 127 | - Map<Object, Object> udtValues = Maps.newHashMapWithExpectedSize(entities.size()); | |
| 128 | - for (Entry<K, V> entry : entities.entrySet()) { | |
| 129 | - Object key = (keyMapper == null) ? entry.getKey() : keyMapper.toUDT(entry.getKey()); | |
| 130 | - Object value = (valueMapper == null) ? entry.getValue() : valueMapper.toUDT(entry.getValue()); | |
| 131 | - udtValues.put(key, value); | |
| 132 | - } | |
| 133 | - return udtValues; | |
| 134 | - } | |
| 135 | - | |
| 136 | 88 | T toEntity(UDTValue udtValue) { |
| 137 | 89 | T entity = entityMapper.newEntity(); |
| 138 | 90 | for (ColumnMapper<T> cm : entityMapper.allColumns()) { |
| @@ -143,30 +95,93 @@ | ||
| 143 | 95 | return entity; |
| 144 | 96 | } |
| 145 | 97 | |
| 146 | - List<T> toEntities(List<UDTValue> udtValues) { | |
| 147 | - List<T> entities = new ArrayList<T>(udtValues.size()); | |
| 148 | - for (UDTValue udtValue : udtValues) { | |
| 149 | - entities.add(toEntity(udtValue)); | |
| 98 | + /** | |
| 99 | + * Handles a (possibly nested) collection where some of the elements are domain classes that | |
| 100 | + * must be converted to {@code UDTValue} instances. | |
| 101 | + */ | |
| 102 | + @SuppressWarnings("unchecked") | |
| 103 | + static Object convertEntitiesToUDTs(Object value, InferredCQLType type) { | |
| 104 | + if (value == null) | |
| 105 | + return null; | |
| 106 | + | |
| 107 | + if (!type.containsMappedUDT) | |
| 108 | + return value; | |
| 109 | + | |
| 110 | + if (type.udtMapper != null) | |
| 111 | + return type.udtMapper.toUDT(value); | |
| 112 | + | |
| 113 | + if (type.dataType.getName() == DataType.Name.LIST) { | |
| 114 | + InferredCQLType elementType = type.childTypes.get(0); | |
| 115 | + List<Object> result = new ArrayList<Object>(); | |
| 116 | + for (Object element : (List<Object>)value) | |
| 117 | + result.add(convertEntitiesToUDTs(element, elementType)); | |
| 118 | + return result; | |
| 119 | + } | |
| 120 | + | |
| 121 | + if (type.dataType.getName() == DataType.Name.SET) { | |
| 122 | + InferredCQLType elementType = type.childTypes.get(0); | |
| 123 | + Set<Object> result = new LinkedHashSet<Object>(); | |
| 124 | + for (Object element : (Set<Object>)value) | |
| 125 | + result.add(convertEntitiesToUDTs(element, elementType)); | |
| 126 | + return result; | |
| 150 | 127 | } |
| 151 | - return entities; | |
| 152 | - } | |
| 153 | 128 | |
| 154 | - Set<T> toEntities(Set<UDTValue> udtValues) { | |
| 155 | - Set<T> entities = Sets.newHashSetWithExpectedSize(udtValues.size()); | |
| 156 | - for (UDTValue udtValue : udtValues) { | |
| 157 | - entities.add(toEntity(udtValue)); | |
| 129 | + if (type.dataType.getName() == DataType.Name.MAP) { | |
| 130 | + InferredCQLType keyType = type.childTypes.get(0); | |
| 131 | + InferredCQLType valueType = type.childTypes.get(1); | |
| 132 | + Map<Object, Object> result = new LinkedHashMap<Object, Object>(); | |
| 133 | + for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet()) | |
| 134 | + result.put( | |
| 135 | + convertEntitiesToUDTs(entry.getKey(), keyType), | |
| 136 | + convertEntitiesToUDTs(entry.getValue(), valueType) | |
| 137 | + ); | |
| 138 | + return result; | |
| 158 | 139 | } |
| 159 | - return entities; | |
| 140 | + throw new IllegalArgumentException("Error converting " + value); | |
| 160 | 141 | } |
| 161 | 142 | |
| 143 | + /** | |
| 144 | + * Handles a (possibly nested) collection where some of the elements are {@code UDTValue} | |
| 145 | + * instances that must be converted to domain classes. | |
| 146 | + */ | |
| 162 | 147 | @SuppressWarnings("unchecked") |
| 163 | - static <K, V> Map<K, V> toEntities(Map<Object, Object> udtValues, UDTMapper<K> keyMapper, UDTMapper<V> valueMapper) { | |
| 164 | - Map<K, V> entities = Maps.newHashMapWithExpectedSize(udtValues.size()); | |
| 165 | - for (Entry<Object, Object> entry : udtValues.entrySet()) { | |
| 166 | - K key = (keyMapper == null) ? (K) entry.getKey() : keyMapper.toEntity((UDTValue) entry.getKey()); | |
| 167 | - V value = (valueMapper == null) ? (V) entry.getValue() : valueMapper.toEntity((UDTValue)entry.getValue()); | |
| 168 | - entities.put(key, value); | |
| 148 | + static Object convertUDTsToEntities(Object value, InferredCQLType type) { | |
| 149 | + if (value == null) | |
| 150 | + return null; | |
| 151 | + | |
| 152 | + if (!type.containsMappedUDT) | |
| 153 | + return value; | |
| 154 | + | |
| 155 | + if (type.udtMapper != null) | |
| 156 | + return type.udtMapper.toEntity((UDTValue)value); | |
| 157 | + | |
| 158 | + if (type.dataType.getName() == DataType.Name.LIST) { | |
| 159 | + InferredCQLType elementType = type.childTypes.get(0); | |
| 160 | + List<Object> result = new ArrayList<Object>(); | |
| 161 | + for (Object element : (List<Object>)value) | |
| 162 | + result.add(convertUDTsToEntities(element, elementType)); | |
| 163 | + return result; | |
| 164 | + } | |
| 165 | + | |
| 166 | + if (type.dataType.getName() == DataType.Name.SET) { | |
| 167 | + InferredCQLType elementType = type.childTypes.get(0); | |
| 168 | + Set<Object> result = new LinkedHashSet<Object>(); | |
| 169 | + for (Object element : (Set<Object>)value) | |
| 170 | + result.add(convertUDTsToEntities(element, elementType)); | |
| 171 | + return result; | |
| 172 | + } | |
| 173 | + | |
| 174 | + if (type.dataType.getName() == DataType.Name.MAP) { | |
| 175 | + InferredCQLType keyType = type.childTypes.get(0); | |
| 176 | + InferredCQLType valueType = type.childTypes.get(1); | |
| 177 | + Map<Object, Object> result = new LinkedHashMap<Object, Object>(); | |
| 178 | + for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet()) | |
| 179 | + result.put( | |
| 180 | + convertUDTsToEntities(entry.getKey(), keyType), | |
| 181 | + convertUDTsToEntities(entry.getValue(), valueType) | |
| 182 | + ); | |
| 183 | + return result; | |
| 169 | 184 | } |
| 170 | - return entities; | |
| 185 | + throw new IllegalArgumentException("Error converting " + value); | |
| 171 | 186 | } |
| 172 | 187 | } |
added driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.Collections; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Provides access to package-private members of the core module. | |
| 7 | + */ | |
| 8 | +public class CoreHooks { | |
| 9 | + public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList()); | |
| 10 | +} |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/AnnotationChecksTest.java +25 −2
| @@ -3,15 +3,19 @@ | ||
| 3 | 3 | import java.lang.reflect.Field; |
| 4 | 4 | import java.util.List; |
| 5 | 5 | import java.util.Map; |
| 6 | +import java.util.Set; | |
| 6 | 7 | |
| 7 | 8 | import com.datastax.driver.mapping.annotations.Frozen; |
| 8 | 9 | import com.datastax.driver.mapping.annotations.FrozenValue; |
| 10 | +import com.datastax.driver.mapping.annotations.UDT; | |
| 11 | + | |
| 9 | 12 | import org.testng.annotations.Test; |
| 10 | 13 | |
| 11 | 14 | import static org.testng.Assert.fail; |
| 12 | 15 | |
| 13 | 16 | public class AnnotationChecksTest { |
| 14 | 17 | // Dummy UDT class: |
| 18 | + @UDT(name = "user") | |
| 15 | 19 | public class User { |
| 16 | 20 | } |
| 17 | 21 | |
| @@ -27,11 +31,21 @@ | ||
| 27 | 31 | @FrozenValue |
| 28 | 32 | List<User> listOfFrozenUsers; |
| 29 | 33 | Map<String, Map<String, User>> deeplyNestedUnfrozenUser; |
| 30 | - @Frozen("map<text, map<text, frozen<user>>>") | |
| 34 | + @Frozen("map<text, frozen<map<text, frozen<user>>>>") | |
| 31 | 35 | Map<String, Map<String, User>> deeplyNestedFrozenUser; |
| 32 | 36 | |
| 37 | + Map<String, List<Integer>> mapOfUnfrozenListOfInt; | |
| 38 | + @FrozenValue | |
| 39 | + Map<String, List<Integer>> mapOfFrozenListOfInt; | |
| 40 | + @FrozenValue | |
| 41 | + Map<Integer, List<Set<Integer>>> deeplyNestedUnfrozenSet; | |
| 42 | + @Frozen("map<int, frozen<list<set<int>>>>") | |
| 43 | + Map<Integer, List<Set<Integer>>> deeplyNestedUnfrozenSet2; | |
| 44 | + @Frozen("map<int, frozen<list<frozen<set<int>>>>>") | |
| 45 | + Map<Integer, List<Set<Integer>>> deeplyNestedFrozenSet; | |
| 46 | + | |
| 33 | 47 | @Test(groups = "unit") |
| 34 | - public void checkFrozenTypesTest() throws Exception { | |
| 48 | + public void should_fail_if_udt_not_frozen() throws Exception { | |
| 35 | 49 | checkFrozenTypesTest("string", true); |
| 36 | 50 | checkFrozenTypesTest("frozenString", false); |
| 37 | 51 | checkFrozenTypesTest("listOfStrings", true); |
| @@ -43,6 +57,15 @@ | ||
| 43 | 57 | checkFrozenTypesTest("deeplyNestedFrozenUser", true); |
| 44 | 58 | } |
| 45 | 59 | |
| 60 | + @Test(groups = "unit") | |
| 61 | + public void should_fail_if_nested_collection_not_frozen() throws Exception { | |
| 62 | + checkFrozenTypesTest("mapOfUnfrozenListOfInt", false); | |
| 63 | + checkFrozenTypesTest("mapOfFrozenListOfInt", true); | |
| 64 | + checkFrozenTypesTest("deeplyNestedUnfrozenSet", false); | |
| 65 | + checkFrozenTypesTest("deeplyNestedUnfrozenSet2", false); | |
| 66 | + checkFrozenTypesTest("deeplyNestedFrozenSet", true); | |
| 67 | + } | |
| 68 | + | |
| 46 | 69 | private void checkFrozenTypesTest(String fieldName, boolean expectSuccess) throws Exception { |
| 47 | 70 | Field field = AnnotationChecksTest.class.getDeclaredField(fieldName); |
| 48 | 71 | Exception exception = null; |
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/CQLTypeTest.java +0 −103
| @@ -1,103 +0,0 @@ | ||
| 1 | -package com.datastax.driver.mapping; | |
| 2 | - | |
| 3 | -import org.testng.annotations.Test; | |
| 4 | -import static org.testng.Assert.*; | |
| 5 | - | |
| 6 | -public class CQLTypeTest { | |
| 7 | - @Test(groups = "unit") | |
| 8 | - public void parseSimpleTypeTest() { | |
| 9 | - CQLType type = CQLType.parse(" foo"); | |
| 10 | - assertEquals(type.name, "foo"); | |
| 11 | - assertFalse(type.frozen); | |
| 12 | - assertNull(type.subTypes); | |
| 13 | - } | |
| 14 | - | |
| 15 | - @Test(groups = "unit") | |
| 16 | - public void parseQuotedTypeTest() { | |
| 17 | - CQLType type = CQLType.parse("\"Foo bar\""); | |
| 18 | - assertEquals(type.name, "Foo bar"); | |
| 19 | - assertFalse(type.frozen); | |
| 20 | - assertNull(type.subTypes); | |
| 21 | - } | |
| 22 | - | |
| 23 | - @Test(groups = "unit") | |
| 24 | - public void parseNestedTypeTest() { | |
| 25 | - // list | |
| 26 | - CQLType type = CQLType.parse("list<foo1>"); | |
| 27 | - assertEquals(type.name, "list"); | |
| 28 | - assertFalse(type.frozen); | |
| 29 | - assertEquals(type.subTypes.size(), 1); | |
| 30 | - | |
| 31 | - CQLType subType0 = type.subTypes.get(0); | |
| 32 | - assertEquals(subType0.name, "foo1"); | |
| 33 | - assertFalse(subType0.frozen); | |
| 34 | - assertNull(subType0.subTypes); | |
| 35 | - | |
| 36 | - // map | |
| 37 | - type = CQLType.parse("map < foo , bar >"); | |
| 38 | - assertEquals(type.name, "map"); | |
| 39 | - assertFalse(type.frozen); | |
| 40 | - assertEquals(type.subTypes.size(), 2); | |
| 41 | - | |
| 42 | - subType0 = type.subTypes.get(0); | |
| 43 | - assertEquals(subType0.name, "foo"); | |
| 44 | - assertFalse(subType0.frozen); | |
| 45 | - assertNull(subType0.subTypes); | |
| 46 | - | |
| 47 | - CQLType subType1 = type.subTypes.get(1); | |
| 48 | - assertEquals(subType1.name, "bar"); | |
| 49 | - assertFalse(subType1.frozen); | |
| 50 | - assertNull(subType1.subTypes); | |
| 51 | - | |
| 52 | - } | |
| 53 | - | |
| 54 | - @Test(groups = "unit") | |
| 55 | - public void parseSimpleFrozenTypeTest() { | |
| 56 | - CQLType type = CQLType.parse("frozen<foo_1>"); | |
| 57 | - assertEquals(type.name, "foo_1"); | |
| 58 | - assertTrue(type.frozen); | |
| 59 | - assertNull(type.subTypes); | |
| 60 | - } | |
| 61 | - | |
| 62 | - @Test(groups = "unit") | |
| 63 | - public void parseNestedFrozenTypeTest() { | |
| 64 | - CQLType type = CQLType.parse("list<frozen<foo>>"); | |
| 65 | - assertEquals(type.name, "list"); | |
| 66 | - assertFalse(type.frozen); | |
| 67 | - assertEquals(type.subTypes.size(), 1); | |
| 68 | - | |
| 69 | - CQLType subType0 = type.subTypes.get(0); | |
| 70 | - assertEquals(subType0.name, "foo"); | |
| 71 | - assertTrue(subType0.frozen); | |
| 72 | - assertNull(subType0.subTypes); | |
| 73 | - } | |
| 74 | - | |
| 75 | - @Test(groups = "unit") | |
| 76 | - public void parseDeeplyNestedTypeTest() { | |
| 77 | - // NB: nested collections are not allowed in C* 2.1, but might be in the future, so we want to handle that | |
| 78 | - CQLType type = CQLType.parse("map<text, map<text, frozen<foo>>>"); | |
| 79 | - assertEquals(type.name, "map"); | |
| 80 | - assertFalse(type.frozen); | |
| 81 | - assertEquals(type.subTypes.size(), 2); | |
| 82 | - | |
| 83 | - CQLType subType0 = type.subTypes.get(0); | |
| 84 | - assertEquals(subType0.name, "text"); | |
| 85 | - assertFalse(subType0.frozen); | |
| 86 | - assertNull(subType0.subTypes); | |
| 87 | - | |
| 88 | - CQLType subType1 = type.subTypes.get(1); | |
| 89 | - assertEquals(subType1.name, "map"); | |
| 90 | - assertFalse(subType1.frozen); | |
| 91 | - assertEquals(subType1.subTypes.size(), 2); | |
| 92 | - | |
| 93 | - CQLType subType10 = subType1.subTypes.get(0); | |
| 94 | - assertEquals(subType10.name, "text"); | |
| 95 | - assertFalse(subType10.frozen); | |
| 96 | - assertNull(subType10.subTypes); | |
| 97 | - | |
| 98 | - CQLType subType11 = subType1.subTypes.get(1); | |
| 99 | - assertEquals(subType11.name, "foo"); | |
| 100 | - assertTrue(subType11.frozen); | |
| 101 | - assertNull(subType11.subTypes); | |
| 102 | - } | |
| 103 | -} |
added driver-mapping/src/test/java/com/datastax/driver/mapping/DeclaredFrozenTypeTest.java +103 −0
| @@ -0,0 +1,103 @@ | ||
| 1 | +package com.datastax.driver.mapping; | |
| 2 | + | |
| 3 | +import org.testng.annotations.Test; | |
| 4 | +import static org.testng.Assert.*; | |
| 5 | + | |
| 6 | +public class DeclaredFrozenTypeTest { | |
| 7 | + @Test(groups = "unit") | |
| 8 | + public void parseSimpleTypeTest() { | |
| 9 | + DeclaredFrozenType type = DeclaredFrozenType.parse(" foo"); | |
| 10 | + assertEquals(type.name, "foo"); | |
| 11 | + assertFalse(type.frozen); | |
| 12 | + assertNull(type.subTypes); | |
| 13 | + } | |
| 14 | + | |
| 15 | + @Test(groups = "unit") | |
| 16 | + public void parseQuotedTypeTest() { | |
| 17 | + DeclaredFrozenType type = DeclaredFrozenType.parse("\"Foo bar\""); | |
| 18 | + assertEquals(type.name, "Foo bar"); | |
| 19 | + assertFalse(type.frozen); | |
| 20 | + assertNull(type.subTypes); | |
| 21 | + } | |
| 22 | + | |
| 23 | + @Test(groups = "unit") | |
| 24 | + public void parseNestedTypeTest() { | |
| 25 | + // list | |
| 26 | + DeclaredFrozenType type = DeclaredFrozenType.parse("list<foo1>"); | |
| 27 | + assertEquals(type.name, "list"); | |
| 28 | + assertFalse(type.frozen); | |
| 29 | + assertEquals(type.subTypes.size(), 1); | |
| 30 | + | |
| 31 | + DeclaredFrozenType subType0 = type.subTypes.get(0); | |
| 32 | + assertEquals(subType0.name, "foo1"); | |
| 33 | + assertFalse(subType0.frozen); | |
| 34 | + assertNull(subType0.subTypes); | |
| 35 | + | |
| 36 | + // map | |
| 37 | + type = DeclaredFrozenType.parse("map < foo , bar >"); | |
| 38 | + assertEquals(type.name, "map"); | |
| 39 | + assertFalse(type.frozen); | |
| 40 | + assertEquals(type.subTypes.size(), 2); | |
| 41 | + | |
| 42 | + subType0 = type.subTypes.get(0); | |
| 43 | + assertEquals(subType0.name, "foo"); | |
| 44 | + assertFalse(subType0.frozen); | |
| 45 | + assertNull(subType0.subTypes); | |
| 46 | + | |
| 47 | + DeclaredFrozenType subType1 = type.subTypes.get(1); | |
| 48 | + assertEquals(subType1.name, "bar"); | |
| 49 | + assertFalse(subType1.frozen); | |
| 50 | + assertNull(subType1.subTypes); | |
| 51 | + | |
| 52 | + } | |
| 53 | + | |
| 54 | + @Test(groups = "unit") | |
| 55 | + public void parseSimpleFrozenTypeTest() { | |
| 56 | + DeclaredFrozenType type = DeclaredFrozenType.parse("frozen<foo_1>"); | |
| 57 | + assertEquals(type.name, "foo_1"); | |
| 58 | + assertTrue(type.frozen); | |
| 59 | + assertNull(type.subTypes); | |
| 60 | + } | |
| 61 | + | |
| 62 | + @Test(groups = "unit") | |
| 63 | + public void parseNestedFrozenTypeTest() { | |
| 64 | + DeclaredFrozenType type = DeclaredFrozenType.parse("list<frozen<foo>>"); | |
| 65 | + assertEquals(type.name, "list"); | |
| 66 | + assertFalse(type.frozen); | |
| 67 | + assertEquals(type.subTypes.size(), 1); | |
| 68 | + | |
| 69 | + DeclaredFrozenType subType0 = type.subTypes.get(0); | |
| 70 | + assertEquals(subType0.name, "foo"); | |
| 71 | + assertTrue(subType0.frozen); | |
| 72 | + assertNull(subType0.subTypes); | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test(groups = "unit") | |
| 76 | + public void parseDeeplyNestedTypeTest() { | |
| 77 | + // NB: nested collections are not allowed in C* 2.1, but might be in the future, so we want to handle that | |
| 78 | + DeclaredFrozenType type = DeclaredFrozenType.parse("map<text, map<text, frozen<foo>>>"); | |
| 79 | + assertEquals(type.name, "map"); | |
| 80 | + assertFalse(type.frozen); | |
| 81 | + assertEquals(type.subTypes.size(), 2); | |
| 82 | + | |
| 83 | + DeclaredFrozenType subType0 = type.subTypes.get(0); | |
| 84 | + assertEquals(subType0.name, "text"); | |
| 85 | + assertFalse(subType0.frozen); | |
| 86 | + assertNull(subType0.subTypes); | |
| 87 | + | |
| 88 | + DeclaredFrozenType subType1 = type.subTypes.get(1); | |
| 89 | + assertEquals(subType1.name, "map"); | |
| 90 | + assertFalse(subType1.frozen); | |
| 91 | + assertEquals(subType1.subTypes.size(), 2); | |
| 92 | + | |
| 93 | + DeclaredFrozenType subType10 = subType1.subTypes.get(0); | |
| 94 | + assertEquals(subType10.name, "text"); | |
| 95 | + assertFalse(subType10.frozen); | |
| 96 | + assertNull(subType10.subTypes); | |
| 97 | + | |
| 98 | + DeclaredFrozenType subType11 = subType1.subTypes.get(1); | |
| 99 | + assertEquals(subType11.name, "foo"); | |
| 100 | + assertTrue(subType11.frozen); | |
| 101 | + assertNull(subType11.subTypes); | |
| 102 | + } | |
| 103 | +} |
added driver-mapping/src/test/java/com/datastax/driver/mapping/InferredCQLTypeTest.java +94 −0
| @@ -0,0 +1,94 @@ | ||
| 1 | +package com.datastax.driver.mapping; | |
| 2 | + | |
| 3 | +import java.lang.reflect.Field; | |
| 4 | +import java.util.List; | |
| 5 | +import java.util.Map; | |
| 6 | +import java.util.Set; | |
| 7 | + | |
| 8 | +import org.testng.annotations.BeforeClass; | |
| 9 | +import org.testng.annotations.Test; | |
| 10 | + | |
| 11 | +import static org.mockito.Mockito.mock; | |
| 12 | +import static org.mockito.Mockito.when; | |
| 13 | + | |
| 14 | +import com.datastax.driver.core.CoreHooks; | |
| 15 | +import com.datastax.driver.core.DataType; | |
| 16 | +import com.datastax.driver.core.UserType; | |
| 17 | +import com.datastax.driver.mapping.annotations.UDT; | |
| 18 | + | |
| 19 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 20 | + | |
| 21 | +public class InferredCQLTypeTest { | |
| 22 | + MappingManager manager; | |
| 23 | + UDTMapper mockMapper; | |
| 24 | + UserType mockUDTType = CoreHooks.MOCK_USER_TYPE; | |
| 25 | + | |
| 26 | + @BeforeClass(groups = "unit") | |
| 27 | + @SuppressWarnings("unchecked") | |
| 28 | + public void setup() { | |
| 29 | + mockMapper = mock(UDTMapper.class); | |
| 30 | + when(mockMapper.getUserType()).thenReturn(mockUDTType); | |
| 31 | + | |
| 32 | + manager = mock(MappingManager.class); | |
| 33 | + when(manager.udtMapper(MockUDT.class)).thenReturn(mockMapper); | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Test(groups = "unit") | |
| 37 | + public void should_parse_collections_of_primitives() throws Exception { | |
| 38 | + InferredCQLType instance = newInstanceForField("listOfIntegers"); | |
| 39 | + assertThat(instance.dataType).isEqualTo(DataType.list(DataType.cint())); | |
| 40 | + assertThat(instance.containsMappedUDT).isFalse(); | |
| 41 | + assertThat(instance.udtMapper).isNull(); | |
| 42 | + | |
| 43 | + instance = newInstanceForField("setOfStrings"); | |
| 44 | + assertThat(instance.dataType).isEqualTo(DataType.set(DataType.text())); | |
| 45 | + assertThat(instance.containsMappedUDT).isFalse(); | |
| 46 | + assertThat(instance.udtMapper).isNull(); | |
| 47 | + | |
| 48 | + instance = newInstanceForField("mapOfIntegerToString"); | |
| 49 | + assertThat(instance.dataType).isEqualTo(DataType.map(DataType.cint(), DataType.text())); | |
| 50 | + assertThat(instance.containsMappedUDT).isFalse(); | |
| 51 | + assertThat(instance.udtMapper).isNull(); | |
| 52 | + } | |
| 53 | + | |
| 54 | + @Test(groups = "unit") | |
| 55 | + public void should_parse_collection_containing_UDT() throws Exception { | |
| 56 | + InferredCQLType instance = newInstanceForField("listOfUDT"); | |
| 57 | + assertThat(instance.dataType).isEqualTo(DataType.list(mockUDTType)); | |
| 58 | + assertThat(instance.containsMappedUDT).isTrue(); | |
| 59 | + assertThat(instance.udtMapper).isNull(); | |
| 60 | + assertThat(instance.childTypes.get(0).udtMapper).isEqualTo(mockMapper); | |
| 61 | + | |
| 62 | + instance = newInstanceForField("complexMap"); | |
| 63 | + assertThat(instance.dataType).isEqualTo(DataType.map( | |
| 64 | + DataType.list(DataType.cint()), | |
| 65 | + DataType.map(DataType.text(), DataType.set(mockUDTType)) | |
| 66 | + )); | |
| 67 | + assertThat(instance.containsMappedUDT).isTrue(); | |
| 68 | + assertThat(instance.udtMapper).isNull(); | |
| 69 | + InferredCQLType key = instance.childTypes.get(0); | |
| 70 | + assertThat(key.containsMappedUDT).isFalse(); | |
| 71 | + assertThat(key.udtMapper).isNull(); | |
| 72 | + InferredCQLType value = instance.childTypes.get(1); | |
| 73 | + assertThat(value.containsMappedUDT).isTrue(); | |
| 74 | + assertThat(value.udtMapper).isNull(); | |
| 75 | + assertThat(value.childTypes.get(0).containsMappedUDT).isFalse(); | |
| 76 | + assertThat(value.childTypes.get(1).containsMappedUDT).isTrue(); | |
| 77 | + assertThat(value.childTypes.get(1).childTypes.get(0).udtMapper).isEqualTo(mockMapper); | |
| 78 | + } | |
| 79 | + | |
| 80 | + private InferredCQLType newInstanceForField(String name) throws NoSuchFieldException { | |
| 81 | + Field field = InferredCQLTypeTest.class.getDeclaredField(name); | |
| 82 | + return InferredCQLType.from(field, manager); | |
| 83 | + } | |
| 84 | + | |
| 85 | + @UDT(name = "mock") | |
| 86 | + static class MockUDT { | |
| 87 | + } | |
| 88 | + | |
| 89 | + List<Integer> listOfIntegers; | |
| 90 | + Set<String> setOfStrings; | |
| 91 | + Map<Integer, String> mapOfIntegerToString; | |
| 92 | + List<MockUDT> listOfUDT; | |
| 93 | + Map<List<Integer>, Map<String, Set<MockUDT>>> complexMap; | |
| 94 | +} | |
| No newline at the end of the file |
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +144 −0
| @@ -0,0 +1,144 @@ | ||
| 1 | +package com.datastax.driver.mapping; | |
| 2 | + | |
| 3 | +import java.util.Collection; | |
| 4 | +import java.util.Map; | |
| 5 | + | |
| 6 | +import com.google.common.collect.ImmutableMap; | |
| 7 | +import com.google.common.collect.Lists; | |
| 8 | +import org.testng.annotations.Test; | |
| 9 | + | |
| 10 | +import com.datastax.driver.core.CCMBridge; | |
| 11 | +import com.datastax.driver.core.ResultSet; | |
| 12 | +import com.datastax.driver.mapping.annotations.*; | |
| 13 | + | |
| 14 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 15 | + | |
| 16 | +public class MapperNestedCollectionsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 17 | + | |
| 18 | + @Override | |
| 19 | + protected Collection<String> getTableDefinitions() { | |
| 20 | + return Lists.newArrayList( | |
| 21 | + "CREATE TYPE testType(i int)", | |
| 22 | + "CREATE TABLE testTable (k int primary key, " | |
| 23 | + + "m1 map<text, frozen<map<int, int>>>, " // nested collection | |
| 24 | + + "m2 map<text, frozen<map<int, frozen<testType>>>>)" // nested collection with UDT | |
| 25 | + ); | |
| 26 | + } | |
| 27 | + | |
| 28 | + @Test(groups = "short") | |
| 29 | + public void should_map_fields_to_nested_collections() { | |
| 30 | + Mapper<TestTable> mapper = new MappingManager(session).mapper(TestTable.class); | |
| 31 | + | |
| 32 | + TestTable testTable = new TestTable(); | |
| 33 | + testTable.setK(1); | |
| 34 | + testTable.setM1(ImmutableMap.<String, Map<Integer, Integer>>of("bar", ImmutableMap.of(1, 2))); | |
| 35 | + testTable.setM2(ImmutableMap.<String, Map<Integer, TestType>>of("bar", ImmutableMap.of(1, new TestType(2)))); | |
| 36 | + | |
| 37 | + mapper.save(testTable); | |
| 38 | + | |
| 39 | + TestTable testTable2 = mapper.get(1); | |
| 40 | + assertThat(testTable2.getM1()).isEqualTo(testTable.getM1()); | |
| 41 | + assertThat(testTable2.getM2()).isEqualTo(testTable.getM2()); | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Test(groups = "short") | |
| 45 | + public void should_map_accessor_params_to_nested_collections() { | |
| 46 | + MappingManager manager = new MappingManager(session); | |
| 47 | + Mapper<TestTable> mapper = manager.mapper(TestTable.class); | |
| 48 | + TestAccessor accessor = manager.createAccessor(TestAccessor.class); | |
| 49 | + | |
| 50 | + TestTable testTable = new TestTable(); | |
| 51 | + testTable.setK(1); | |
| 52 | + mapper.save(testTable); | |
| 53 | + | |
| 54 | + Map<String, Map<Integer, Integer>> m1 = ImmutableMap.<String, Map<Integer, Integer>>of("bar", ImmutableMap.of(1, 2)); | |
| 55 | + Map<String, Map<Integer, TestType>> m2 = ImmutableMap.<String, Map<Integer, TestType>>of("bar", ImmutableMap.of(1, new TestType(2))); | |
| 56 | + accessor.setM1(1, m1); | |
| 57 | + accessor.setM2(1, m2); | |
| 58 | + | |
| 59 | + TestTable testTable2 = mapper.get(1); | |
| 60 | + assertThat(testTable2.getM1()).isEqualTo(m1); | |
| 61 | + assertThat(testTable2.getM2()).isEqualTo(m2); | |
| 62 | + } | |
| 63 | + | |
| 64 | + @UDT(keyspace = "ks", name = "testType") | |
| 65 | + public static class TestType { | |
| 66 | + private int i; | |
| 67 | + | |
| 68 | + public TestType() { | |
| 69 | + } | |
| 70 | + | |
| 71 | + public TestType(int i) { | |
| 72 | + this.i = i; | |
| 73 | + } | |
| 74 | + | |
| 75 | + public int getI() { | |
| 76 | + return i; | |
| 77 | + } | |
| 78 | + | |
| 79 | + public void setI(int i) { | |
| 80 | + this.i = i; | |
| 81 | + } | |
| 82 | + | |
| 83 | + @Override | |
| 84 | + public boolean equals(Object other) { | |
| 85 | + if (this == other) | |
| 86 | + return true; | |
| 87 | + if (other instanceof TestType) { | |
| 88 | + TestType that = (TestType)other; | |
| 89 | + return this.i == that.i; | |
| 90 | + } | |
| 91 | + return false; | |
| 92 | + } | |
| 93 | + | |
| 94 | + @Override | |
| 95 | + public int hashCode() { | |
| 96 | + return i; | |
| 97 | + } | |
| 98 | + } | |
| 99 | + | |
| 100 | + @Table(keyspace = "ks", name = "testTable") | |
| 101 | + public static class TestTable { | |
| 102 | + @PartitionKey | |
| 103 | + private int k; | |
| 104 | + | |
| 105 | + @Frozen("map<text, frozen<map<int, int>>>") | |
| 106 | + private Map<String, Map<Integer, Integer>> m1; | |
| 107 | + | |
| 108 | + @Frozen("map<text, frozen<map<int, frozen<testType>>>>") | |
| 109 | + private Map<String, Map<Integer, TestType>> m2; | |
| 110 | + | |
| 111 | + public int getK() { | |
| 112 | + return k; | |
| 113 | + } | |
| 114 | + | |
| 115 | + public void setK(int k) { | |
| 116 | + this.k = k; | |
| 117 | + } | |
| 118 | + | |
| 119 | + public Map<String, Map<Integer, Integer>> getM1() { | |
| 120 | + return m1; | |
| 121 | + } | |
| 122 | + | |
| 123 | + public void setM1(Map<String, Map<Integer, Integer>> m1) { | |
| 124 | + this.m1 = m1; | |
| 125 | + } | |
| 126 | + | |
| 127 | + public Map<String, Map<Integer, TestType>> getM2() { | |
| 128 | + return m2; | |
| 129 | + } | |
| 130 | + | |
| 131 | + public void setM2(Map<String, Map<Integer, TestType>> m2) { | |
| 132 | + this.m2 = m2; | |
| 133 | + } | |
| 134 | + } | |
| 135 | + | |
| 136 | + @Accessor | |
| 137 | + public static interface TestAccessor { | |
| 138 | + @Query("UPDATE testTable SET m1 = :m1 WHERE k = :k") | |
| 139 | + ResultSet setM1(@Param("k") int k, @Param("m1") Map<String, Map<Integer, Integer>> m1); | |
| 140 | + | |
| 141 | + @Query("UPDATE testTable SET m2 = :m2 WHERE k = :k") | |
| 142 | + ResultSet setM2(@Param("k") int k, @Param("m2") Map<String, Map<Integer, TestType>> m2); | |
| 143 | + } | |
| 144 | +} |